Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果我做:
os.chdir(path) f = open(file,"r") lines = f.readlines() print "without assignment " + str(len(f.readlines())) print "with assignment " + str(len(lines))
我希望输出是相同的,但它不是:
without assignment 0 with assigment 1268
为什么是这样?
文件对象f是文件行的迭代器。f.readlines()将文件光标移动到末尾,但保存行,lines这就是第二个示例适用于您的原因。第一个示例不起作用,因为您已到达文件末尾并且没有可读取的行。f.seek(0)如果您想完成这项工作,您可以使用将光标移回文件的开头。
f
f.readlines()
lines
f.seek(0)