Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 ?

like image 412
Akki Avatar asked Mar 21 '26 12:03

Akki


1 Answers

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.

like image 51
Jean-François Fabre Avatar answered Mar 24 '26 01:03

Jean-François Fabre