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:
/tempFolder/test.txt
only contains the first set of bytes that were written.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!
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