如何在Python中获取当前打开文件的行号?

如何在Python中获取当前打开文件的行号?

Python不直接支持此功能。您可以编写一个包装器类来实现。例如,

class FileLineWrapper(object):
    def __init__(self, file):
        self.f = file
        self.curr_line = 0
    def close(self):
        return self.f.close()
    def readline(self):
        self.curr_line += 1
        return self.f.readline()
    # to allow using in 'with' statements
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
Python

并使用上述代码:

f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)
Python

这将输出:1

如果您仅使用readline方法,则还有其他方法可以跟踪行号。例如,

f=open("my_file", "r")
for line_no, line in enumerate(f):
    print line_no
f.close()
Python

阅读更多:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册