[英]Writing a file in python in a key=value1,…valuen format
I have a existing file /tmp/ps/snaps.txt It has following data: 我有一个现有的文件/tmp/ps/snaps.txt它有以下数据:
key=default_value
I want the contents of this file to be: 我希望这个文件的内容是:
key=default_value,value,value.....valuen
My code for this is (This runs everytime the main python code runs): 我的代码是(每次运行主python代码时运行):
with open("/tmp/ps/snaps.txt", "a+") as text_file:
text_file.write("value")
But the output I get is : 但我得到的输出是:
key=default_value,
value,value.....value
Basically I dont want my values written on the next line, Is there any solution for this ? 基本上我不希望我的值写在下一行,有什么解决方案吗?
The line-terminator at the end of the original file is preventing you from appending on the same line. 原始文件末尾的行终止符阻止您追加到同一行。
You have 3 options: 你有3个选择:
remove that line terminator: your code will work as-is 删除该行终止符:您的代码将按原样运行
open file in append mode as you do, seek back past the linefeed, and write from there (putting a linefeed for the next time or last char(s) will be overwritten: 以附加模式打开文件,回过去换行,然后从那里写入(下次放入换行符或最后一个字符将被覆盖:
code: 码:
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()
) and write the contents + the extra contents. str.rstrip()
最后一个换行符(使用str.rstrip()
)并写入内容+额外的内容。 The stablest option if you can afford the memory+read overhead for the existing contents. code: 码:
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))
option 2 is a hack because it tries to edit a text file in read/write, not very good, but demonstrates that it can be done. 选项2是一个黑客,因为它试图在读/写中编辑文本文件,不是很好,但证明它可以完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.