Search code examples
pythonfile-iofilesystemspython-3.5file-move

How to keep writing in a moved file with the same file object?


If I open a file

fileObj = open(test.txt, 'wb+')

and write some stuff in it

fileObj.write(someBytes)

then decide to move it somewhere else

shutil.move('test.txt', '/tempFolder')

and then keep writing in it

fileObj.write(someMoreBytes)

what happens?

A couple observations:

  1. It seems like the file at /tempFolder/test.txt only contains the first set of bytes that were written.
  2. After the file has been moved, it seems like the first set of bytes are deleted from the file object
  3. Subsequent writing on the file object after the file has been moved do not seem to create a new file on disk at test.txt, so what happens with those bytes? They stay in memory in the file object?

Now my main question is: how do I keep the same file object to write on the moved file? Because essentially the file is the same, it has only change location. Or is that not possible?

Thanks for the help!


Solution

  • after moving your file shutil.move('test.txt', '/tempFolder'), and want to continue adding bytes to it, you will need to create a new variable, indicating the new file location.

    Since you moved the file to a new locations, fileObj.write(someMoreBytes) is not writing bytes anymore since the object you originally created has been moved. so you would have to reopen a new file to "continue" writing bytes into it or specify the new location as indicated above, to add bytes to the existing file.

    For Ex:

    import os
    f=open('existingfile.txt', 'wb+')
    
    f.write('somebytes')
    f.close()
    os.rename('currentPath\existingfile.txt', 'NewPath\existingfile.txt')
    
    #reopen file - Repeat