The root of your problem is that you are trying to read and write to the same file. You need to create a new file.
However, there are several other things that you must first clean up ...
First, you can simplify the process by simply looping through the file object directly, instead of using a while loop. For example:.
flags = {'1oMZgkoaz3o': 'flag1', 'tJuLnRrAcs0': 'flag2'}
In this example, we simply print the desired result. If the file is small, we can easily do something like this
flags = {'1oMZgkoaz3o': 'flag1', 'tJuLnRrAcs0': 'flag2'} with open('test.txt', 'r') as infile: # Load the entire contents of the file into memory... lines = infile.readlines() with open('test.txt', 'w') as outfile: for line in lines: print line line = line.strip().split() line.append(flags.get(line[0], '')) outfile.write(' '.join(line) + '\n')
However, if it is a large file, we may not want to read the entire copy in memory.
In this case, we want to iterate over the source file and write to another file. Then we need to rename the new file to the original file name.
If we want to be very careful, we would do something like the following:
import os flags = {'1oMZgkoaz3o': 'flag1', 'tJuLnRrAcs0': 'flag2'} infile = open('test.txt', 'r') outfile = open('test2.txt', 'w') try: # Try to do this... for line in infile: line = line.strip().split() line.append(flags.get(line[0], '')) outfile.write(' '.join(line) + '\n') finally: # Do this no matter what... infile.close() outfile.close() # If nothing goes wrong, do this... os.remove('test.txt') os.rename('test2.txt', 'test.txt')
The try:... finally:...
essentially manually does what the with
statement does for the file object. This may be a little cleaner than nesting two with statements in this particular case, but I mostly use it to show an alternative (older) syntax for this. Ideally, you probably write this piece of code similar to this:
import os def main(): flags = {'1oMZgkoaz3o': 'flag1', 'tJuLnRrAcs0': 'flag2'} with open('test.txt', 'r') as infile: with open('test2.txt', 'w') as outfile: append_flags(infile, outfile, flags) os.remove('test.txt') os.rename('test2.txt', 'test.txt') def append_flags(infile, outfile, flags): for line in infile: line = line.strip().split() line.append(flags.get(line[0], '')) outfile.write(' '.join(line) + '\n') main()
However, we are clearly becoming more complex the further we go with this.
In your case, the second example (reading the entire file into memory and then writing over the original file) is probably what you want.