[英]I don't understand why i can't get readline function in python to work in this program. What am I doing wrong?
在這個程序中,我想將單獨的行保存到一個變量中,但是當我嘗試打印該變量時,它只返回一個空格,而不是文件中行上的內容。 抱歉,我對編程很陌生
file=open('emails.txt','w+')
while True:
email=input('pls input your email adress: ')
file.write(email)
file.write('\n')
more=input('would you like more emails to be processed? ')
if more == 'yes' or more == 'ye' or more == 'y' or more == 'yep' or more == 'Y':
continue
elif more == 'no' or more == 'nah' or more == 'n' or more == 'N' or more == 'nope':
file.close()
print('this is the list of emails so far')
file=open('emails.txt','r')
print(file.read()) #this reads the whole file and it works
email_1=file.readline(1) #this is meant to save the 1st line to a variable but doesn't work!!!
print(email_1) #this is meant to print it but just returns a space
file.close()
print('end of program')
首先,您應該使用with
來處理文件。
其次,您打開文件進行打印並讀取其所有內容: print(file.read())
在這一行之后,cursor 位於文件末尾,因此下次嘗試從文件中讀取內容時,會得到空字符串。
要修復它,您幾乎沒有其他選擇。
第一個選項:
添加file.seek(0, 0)
將 cursor 移回文件的開頭,因此當您執行file.readline
時,您將真正讀取文件行。
此外, file.readline(1)
應改為file.readline()
第二種選擇:
只需將所有文件內容讀入列表,打印它然后打印列表中的第一個條目(文件中的第一行......)
file = open('emails.txt', 'r')
content = file.readlines()
print(*content, sep='')
email_1 = content[0]
print(email_1)
正如上面第一條評論中提到的,file.read() 調用將文件指針移動到文件末尾,因此沒有數據可供 readline() 讀取。
而且,您正在調用 readline(1) 它將讀取一個字節,而不是一行。
好吧,我會嘗試with
所以嘗試像這樣實現它:
> with open('emails.txt','w+') as output_file:
while True:
# and then rest of your code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.