Nikhil Sahu
Nikhil Sahu

Reputation: 2621

Writing to the end of specific line in python

I have a text file that contains key value pairs separated by a tab like this:

KEY\tVALUE

I have opened this file in append mode(a+) so I can both read and write. Now it may happen that a particular key has more than 1 value. For that I want to be able to go to that particular key and write the next value beside original one separated by a some delimiter(or ,). Here is what I wish to do:

import io
ft = io.open("test.txt",'a+')
ft.seek(0)
for line in ft:
    if (line.split('\t')[0] == "querykey"):
        ft.write(unicode("nextvalue"));#Write the another key value beside the original one

Now there are two problems with it:

  1. I will iterate through the file to see on which line the key is present(Is there a faster way?)
  2. I will write a string to the end of that line.

I would be grateful if I can get help with the second point.

The write function always writes at the end of file. How should I write to the end of a specific line? I have searched and have not got very clear answers as to how to do that

Upvotes: 1

Views: 3142

Answers (1)

Hasan Ramezani
Hasan Ramezani

Reputation: 5194

You can read whole of file content, do your edit and write edited content to file.

with open('test.txt') as f:
    lines = f.readlines()

f= open('test.txt', 'w')#open file for write
for line in lines:
    if line.split('\t')[0] == "querykey":
        line = line + ',newkey'

    f.write('\n'.join(lines))

Upvotes: 1

Related Questions