简体   繁体   中英

Writing a file in python in a key=value1,…valuen format

I have a existing file /tmp/ps/snaps.txt It has following data:

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):

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:

  1. remove that line terminator: your code will work as-is

  2. 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))
  1. read the file fully, strip the last linefeed (using str.rstrip() ) and write the contents + the extra contents. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM