[英]why getting lis index out of range error while reading file with readlines()?
我只是一個 python 初學者,所以我想練習讀寫文件。 (我正在使用 python 3)
Decision = input("""Would you like to 'Write' (W)?
\nWould you like to 'Read' (R)?""")
if Decision == "W":
fileInput = input("What file Would you like to Write to?")
write(fileInput)
elif Decision == "R":
fileInput = input("What file would you like to Read?")
lineNoInput = input("How many lines would you like to read?")
read(fileInput, lineNoInput)
我想制作一個讓你讀寫文件的程序。 我還沒有寫信給他們,但是我正在做一個 read() function ,它不斷吐出錯誤。
def read(file, lineNo):
fileName = file + ".txt"
text_file = open(fileName, "r")
lineNo = int(lineNo)
for x in range(0, lineNo - 1):
print(text_file.readlines()[x])
text_file.close()
由於某種我無法解決的原因,決定讀取多少行的用戶輸入不斷吐出索引錯誤。
抱歉,如果我的代碼笨拙或無效,正如我之前所說,我仍然是初學者,我將不勝感激任何關於為什么會發生這種情況的意見。
for x in range(0, lineNo - 1): print(text_file.readlines()[x])
調用 readlines 方法的錯誤。 readlines()
方法返回一個列表,其中包含文件中的每一行作為列表項。 這個方法應該只調用一次!! 下次調用它會得到空列表[]
如果您想逐行讀取文件,則通常使用上下文管理器來讀取文件。
從技術上講,在 Python 中,迭代器是實現iterator protocol
的 object,它由方法__iter__()
和__next__()
組成。 由於文件遵循iterator protocol
,您可以使用 for 循環讀取它們:
with open (fileName,'r') as fP:
for line in fp:
#do work
無需調用 close()。 這是在退出 with 塊后由上下文管理器處理的,文件將被關閉。
為了限制要讀取的行數,它在遍歷文件時簡單地使用行計數器:
lines_num = 10
with open (fileName,'r') as fP:
for line in fp:
#do work
lines_num -= 1
if not lines_num: break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.