无法使用使用"打开(文件名)"打开两次的同一文件工作



没有错误,但for循环不起作用。

textfile = open(path+'\z.txt','r')
print(textfile.read())                                      #this works
for a in range(len(textfile.read().split())):               #this doesn't
print(a)

当您对open()返回的文件对象调用read()时;直到EOF(文件结束(为止的所有字节都被返回";。

这意味着,一旦您调用read(),它将读取该文件直到结束,并且";"停留";在文件末尾。

如果你的文件不是太大,那么最好将read()的结果存储在一个variable:中

textfile = open(path_to_file, 'r')
file_content = textfile.read()
print(file_content)
for a in range(len(file_content.split())):
print(a)

更惯用的方法是使用readlines(),例如:

textfile = open(path_to_file, 'r')
# Returns a list of lines, including the newline character:
file_content = textfile.readlines()
for a in range(len(file_content)):
print(a)

或者直接迭代文件对象,例如:

textfile = open(path_to_file, 'r')
for num, line in enumerate(textfile):
print(num)

如果您想使用相同的文件对象再次迭代相同的文件,可以对其调用seek(0),例如:

textfile = open(path_to_file, 'r')
# Print every line in the file:
for line in textfile:
print(line)
# Reset stream position to zero:
textfile.seek(0)
# Print every line in the file again and
# remove newline and whitespace characters before printing:
for line in textfile:
print(line.strip())

最新更新