簡體   English   中英

無法使用兩次以“打開(文件名)”打開的同一文件

[英]Cannot work with the same file open with 'open(filename)' twice

沒有錯誤,但 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()返回的文件 object調用read()時,“返回 EOF(文件結尾)之前的所有字節”。

這意味着,一旦您調用read() ,它將讀取文件直到最后並“停留”在文件末尾。

如果您的文件不是太大,最好將read()的結果存儲在變量中:

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)

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

textfile = open(path_to_file, 'r')

for num, line in enumerate(textfile):
    print(num)

如果你想使用同一個文件 object 再次迭代同一個文件,你可以調用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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM