Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add text in a file with python (without replacing it)

Tags:

python

I have a file with ids and information, like this:

1oMZgkoaz3o 2011-12-29T01:23:00.000Z 9 503 ApolloIsMyCoPilot
nUW1TomCSQg 2011-12-29T01:23:15.000Z 9 348 grea7stuff
tJuLnRrAcs0 2011-12-29T01:26:20.000Z 9 123 AdelGaming
tyi5g0mnPIs 2011-12-29T01:28:07.000Z 9 703 PreferredGaming

and I want to add a flag on some of the line, so if I have a dictionary

flags = {'1oMZgkoaz3o': flag1, 'tJuLnRrAcs0': flag2}

the result I want is

1oMZgkoaz3o 2011-12-29T01:23:00.000Z 9 503 ApolloIsMyCoPilot flag1
nUW1TomCSQg 2011-12-29T01:23:15.000Z 9 348 grea7stuff
tJuLnRrAcs0 2011-12-29T01:26:20.000Z 9 123 AdelGaming flag2
tyi5g0mnPIs 2011-12-29T01:28:07.000Z 9 703 PreferredGaming

So I made this code

l = True
while l is True:
    a = f.readline()
    try a.split(' ')[0] in flags.iterkeys():
        f.seek(-1,1)
        f.write(' '+str(flags[a.split(' ')[0]])+'\n')
        del flags[a.split(' ')[0]]
    except IndexError:
        l = False

so, my Python code could be poor, but the problem is that with this code I'm replacing text, so the file is all messed up. How can I write without replacing? and if you have better ideas for the code, you are welcome...

like image 360
chuse Avatar asked Jan 12 '12 15:01

chuse


People also ask

How do I stop a file overwriting in Python?

An append 'a' rather that write 'w' mode should probably do it so you use the line f = open("text. txt", 'a') .

How do you edit an existing text file in Python?

Use file. Use open(file, mode="r") to open file in read mode. Use file. readlines() to return a list of strings with each string as a line from file . Edit the contents of the list by deleting or adding a line.

Does write in Python overwrite?

Basics of Writing Files in Python Available are two modes, writing to a new file (and overwriting any existing data) and appending data at the end of a file that already exists.


2 Answers

You can't write to the file and "insert". Best approach would be to read your file and write out the contents with modifications to a new file and then rename as necessary.

like image 57
MattH Avatar answered Nov 11 '22 21:11

MattH


I see two problems here:

Reading and writing from/to the same file

This doesn't work too well. It would be better to read from one file and write to another one (this way, you also won't lose data if something goes wrong in your program). Example:

input_file = open('infile.txt', 'r')
output_file = open('outfile.txt', 'w')
for line in input_file:
    line += "transformed"
    output_file.write(line)

Syntactic/semantic errors

You have a syntactic error in your code snippet, the line

try a.split(' ')[0] in flags.iterkeys():

is not valid (and Python should complain about that!).

Some other things to note:

  • in flags.iterkeys() is semantically equivalent to in flags
  • Also, you can just use while l instead of while l is True. Even better, you could drop the flag variable l completely and jump out of the loop with break if an error occurs.

My attempt

input_file = open('infile.txt', 'r')
output_file = open('outfile.txt', 'w')
flags = { ... }

for line in input_file:
    parts = line.strip().split()
    if parts[0] in flags:
        line = line + ' ' + flags[parts[0]]
    output_file.write(line + "\n")

If you know how to use a shell, you could make your life easier if you just use STDIN/STDOUT for data in- and output. You save yourself the file handling then and leave the user more flexibility in how he can use your script.

like image 26
Niklas B. Avatar answered Nov 11 '22 22:11

Niklas B.