如何在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()并将上面的代码用作:
f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)这将给出输出:1
如果仅使用readline方法,还有其他方法可以跟踪行号。例如,
f=open("my_file", "r")
for line_no, line in enumerate(f):
print line_no
f.close()热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短