Difference between shutil.copy2(s,d) and shutil.move(s,d)
Asked Answered
Q

1

6

I have read the documentation provided for shutil.move and copy2. From my understanding move just calls the copy2 function, then calls the remove function, while copy2 calls copy then copystat. That all makes sense, except when I use them I find an interesting caveat (I think) If I use the move function on a file all timestamps on the file stay the same including creation date. If I just call copy2 on the file, then the creation date becomes the current time. Since move is using copy2, why does the creation date not also get changed? Or is the documentation oversimplifying it. It would be nice for a script I have for the copy2 to also copy the original creation timestamp. I have only been working with python for a few days, so I just want to know why the creation timestamp is different between the two function calls. I am on a windows 7 64 if that makes a difference. Ty all in advance.

example:

import os
import shutil
src = os.path.join(os.getcwd(), "copyme.txt")
src2 = os.path.join(os.getcwd(), "moveme.txt")
dst = os.path.join(os.getcwd(), "New Folder")
shutil.copy2(src, dst) #creation date changed
shutil.move(src2, dst) #creation date remains the same as original

I can't figure out why that is happening...

Quadrisect answered 5/8, 2011 at 11:26 Comment(0)
D
5

From my understanding of the shutil documentation, shutil.copystat() doesn't preserve the creation date, it only preserves last access time and last modification date.

Also, shutil.move() uses shutil.copy2() followed by shutil.copystat() only if the source and destination are on different filesystems, otherwise it will use the os.rename() function, which simply moves the file to the new location without creating a new file, and preserves all the file attributes, included the creation date. That's why you are noticing different behaviours.

Dentiform answered 5/8, 2011 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.