0

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!

Maxime Dupré
  • 5,319
  • 7
  • 38
  • 72

2 Answers2

0

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
glls
  • 2,325
  • 1
  • 22
  • 39
0

fobject does not know that you moved the file. You could do this by adding

fileObj = open("tempFolder/test.txt", "wb+")

after the move.

filiphl
  • 921
  • 1
  • 8
  • 15
  • I know that reopening the file would work, but my question is: how can I keep the same file object for the file? I guess your answer is: it's impossible. – Maxime Dupré May 29 '16 at 18:12