The problem with your approach is that you need both an input stream and an output stream that can point to different places in one file. If you want to use f.seek() , you will need to save the position with f.tell() after each read and write. For instance:
f = open(filename, 'r+') while True: i = f.readline() if i == '': break in = f.tell() f.seek(out) f.write(i.rstrip()+"\n") out = f.tell() f.seek(in)
But this is confusing and error prone. If the file is not too large, why not read it all in memory and then write it back?
in = open(filename, 'r') lines = in.read() in.close() out = open(filename, 'w') out.write([line.rstrip()+'\n' for line in lines.split('\n')]) out.close()
If the file is too large to fit in memory, write the lines to a temporary file and then rename the file when you are done:
out = open(filename+'.tmp', 'w') with open(filename, 'r') as f: for i in f: out.write(i.rstrip()+"\n") out.close() os.rename(filename+'.tmp', filename)
source share