簡體   English   中英

Python:循環讀取文件

[英]Python: reading file in loop

sample.txt:

樣品串

碼:

  temp = open("sample.txt", "r") for i in range(0, 4): text = temp.read() print(text) 

輸出:

樣品串

為什么在循環中使用read()會阻止另外4個周期?

正如文檔所說:

If the end of the file has been reached, f.read() will return an empty string ("").

因此,在第一次迭代中已到達文件末尾,然后它返回空字符串。

檢查文件對象方法的文檔

這是因為一旦您對文件運行read ,它就會到達EOF或文件末尾,因此無法再提供更多文本。 因此,它只是給您一個空字符串

因此,讓我通過一個示例進行演示:

temp = open('text.txt')
for i in range(4):
    print("Iteration @ {}".format(i))
    t = temp.read()
    print(t)

text.txt包含:

hello world
cheese cakes

您將得到以下結果:

Iteration @ 0
hello world
cheese cakes
Iteration @ 1

Iteration @ 2

Iteration @ 3

我想這可以做你想要的:

for i in range(0, 4):
   with open("sample.txt", "r") as temp:
       text = temp.read()
       print(text)

user2309239是正確的:不帶參數的read()會讀取所有內容(緩沖區),因此在第一次讀取后,光標位於EOF處。 而且沒有什么可閱讀的了。 我認為您需要temp.read(1),或更具體地講這個問題。 編輯:如果您想在閱讀結束時稍作休息,請將閱讀內容移至while而不是for。

第一次調用read方法實際上返回了文件的所有內容。

如果我理解正確,則您正在嘗試讀取文件的前4行。

您應該通過遍歷文件並在讀取4行之后中斷來做到這一點,或者只是使用readline而不是read

這是使用readline

temp = open("sample.txt", "r")
for i in range(0, 4):
    text = temp.readline()
    print(text)

檢查文檔中的“文件對象上的方法”以獲取有關可以使用哪些方法的更多信息。

如果您試圖讀取整個文件的內容4次,則只需在循環之前將對read方法的調用:

temp = open("sample.txt", "r")
text = temp.read()
for i in range(0, 4):
    print(text)

暫無
暫無

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

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