[英]python Writing to a file
我正在嘗試進行有關在python中寫入文件的第一個任務。 誰能幫我為什么得到以下類型的輸出? 謝謝! 文件log.txt的內容:
文件log.txt的內容應為:
參加,參加。 10、10、22、33,Adios。
我的代碼是:
fileName=input("Give a file name:: ")
filetext=input("Write something: ")
readfile = open("fileName","w")
readfile.write( filetext )
print("Wrote",filetext," to the file",fileName)
readfile.close()
分配:毫不奇怪,本章的第二個練習討論了寫入文件的任務。 創建一個程序,提示用戶輸入文件名“ Give a file name:”,然后輸入“ Write something:”。 此后,程序將用戶給出的字符串寫入文件,並報告“將[輸入]寫入文件[名稱]”。 正常工作時,程序將顯示以下內容:
輸入文件名:log.txt
寫點東西:參加,參加。 10、10、22、33,Adios。
寫出席,出席。 10、10、22、33,Adios。 到文件log.txt。
輸出示例
給一個文件名:: log.txt寫點東西:Attencion,attencion。 10、10、22、33,Adios。 寫出席,出席。 10、10、22、33,Adios。 到文件log.txt
您的問題是您使用字符串"fileName"
而不是變量名fileName
:
readfile = open("fileName","w")
這將創建一個名為fileName
的新文件, 而不使用用戶提供的名稱(例如log.txt
)。 而是使用:
readfile = open(fileName, "w") # remove quote marks
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.