![](/img/trans.png)
[英]How do I change the format of a dictionary to value1;key1; in Python 3.6?
[英]Writing a file in python in a key=value1,…valuen format
我有一個現有的文件/tmp/ps/snaps.txt它有以下數據:
key=default_value
我希望這個文件的內容是:
key=default_value,value,value.....valuen
我的代碼是(每次運行主python代碼時運行):
with open("/tmp/ps/snaps.txt", "a+") as text_file:
text_file.write("value")
但我得到的輸出是:
key=default_value,
value,value.....value
基本上我不希望我的值寫在下一行,有什么解決方案嗎?
原始文件末尾的行終止符阻止您追加到同一行。
你有3個選擇:
刪除該行終止符:您的代碼將按原樣運行
以附加模式打開文件,回過去換行,然后從那里寫入(下次放入換行符或最后一個字符將被覆蓋:
碼:
with open(filename, "a+") as text_file:
text_file.seek(os.path.getsize(filename)-len(os.linesep))
text_file.write("{},\n".format(snapshot_name))
str.rstrip()
最后一個換行符(使用str.rstrip()
)並寫入內容+額外的內容。 如果您能夠承受現有內容的內存+讀取開銷,那么這是最穩定的選項。 碼:
with open(filename,"r") as text_file:
contents = text_file.read().rstrip()
with open(filename,"w") as text_file:
text_file.write(contents)
text_file.write("{},".format(snapshot_name))
選項2是一個黑客,因為它試圖在讀/寫中編輯文本文件,不是很好,但證明它可以完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.