![](/img/trans.png)
[英]TypeError: file must have 'read' and 'readline' attributes run in Python3
[英]Use readline to read txt file python3
我一直在努力工作幾個小時,我無法做到正確,任何幫助將不勝感激! 我的問題是如何使用函數.readline()
來讀取文本文件的結尾? 我知道.readlines()
工作,但我一次嘗試處理一行。
這是我到目前為止我的代碼所擁有的:
a = open("SampleTxt.txt","r")
While True:
a.readline()
我的問題是,當我運行它時,我得到一個無限循環,一旦它不能再讀取一行就不應該停止嗎?
當沒有更多數據可用時, a.readline()
將返回''
空字符串,你需要檢查它然后打破你的while
,例如:
while True:
line = a.readline()
if not line:
break
如果它不是純粹用於學習目的那么你真的應該使用with
語句和for循環來逐行處理文件:
with open('SampleTxt.txt') as fin:
for line in fin:
pass # do something
關於你的意圖更清楚,並且通過使用with
塊,fileobj將在異常或塊結束時釋放。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.