簡體   English   中英

Python:寫入新文件行

[英]Python: Write to new file line

我一直在環顧四周,看看是否能找到一種方法,每次用戶輸入時都可以在文件中寫入新行。 基本代碼是這樣的:

while True:
f = open(server,"w")
initchat = str(input("Chat: "))
chat = str((user + " - " + initchat))
f.write(chat)
f.write("\n")
f.close

許多答案是在字符串中添加\\ n,但這僅在字符串之后添加新行,並且不允許將新行寫入。 我有道理嗎? 任何幫助將不勝感激謝謝

問題是這樣的:

f = open(server,"w")

上面只會寫1行:

您必須使用"a"進行追加。

f = open(server,"a")

順便說一句: while:之后while:您還必須縮進代碼while:

您應該做一個簡單的工作:

with open('file.txt', 'a+') as f:
    initchat = str(input("Chat: "))
    chat = str((user + " - " + initchat))
    f.write(chat+'\n')

暫無
暫無

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

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