我有两个关于python的简单问题:
1.如何在python中获取文件的行数?
2.如何将文件对象中的位置定位到
最后一行容易吗?
最佳答案
行只是由换行符分隔的数据。
1)由于行是可变长度的,您必须读取整个文件才能知道换行符在哪里,因此您可以计算出有多少行:
count = 0
for line in open('myfile'):
count += 1
print count, line # it will be the last line
2)从文件末尾读取块是查找最后一个换行符的最快方法。
def seek_newline_backwards(file_obj, eol_char='\n', buffer_size=200):
if not file_obj.tell(): return # already in beginning of file
# All lines end with \n, including the last one, so assuming we are just
# after one end of line char
file_obj.seek(-1, os.SEEK_CUR)
while file_obj.tell():
ammount = min(buffer_size, file_obj.tell())
file_obj.seek(-ammount, os.SEEK_CUR)
data = file_obj.read(ammount)
eol_pos = data.rfind(eol_char)
if eol_pos != -1:
file_obj.seek(eol_pos - len(data) + 1, os.SEEK_CUR)
break
file_obj.seek(-len(data), os.SEEK_CUR)
你可以这样使用:
f = open('some_file.txt')
f.seek(0, os.SEEK_END)
seek_newline_backwards(f)
print f.tell(), repr(f.readline())
关于python - 关于python的两个简单问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/929887/