Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping file attributes on a copy

I have the situation whereby I want to keep the original attributes on a file (the file creation date etc). Normally when you copy files in Windows, the copy that you make gets new 'modified' dates etc. I have come accross the shutil.copy command — although this doesn't keep the file attributes the same.

I found the following question on Stack Unix, but I was wondering if there was a way for me to do this in Python.

like image 357
Insert Text Here Avatar asked Jul 16 '13 19:07

Insert Text Here


People also ask

How do I copy files without changing the date stamp?

Substitute “C:photos” and “D:photos” for your source and destination folders respectively. options ensure that your original 'date modified' attributes are preserved during the copy. The /E option ensures that subfolders are also copied, including any empty folders you may have in the original location.

How do you copy and preserve permissions?

To preserve permissions when files and folders are copied or moved, use the Xcopy.exe utility with the /O or the /X switch. The object's original permissions will be added to inheritable permissions in the new location.

Which option of copy command will preserve the file attributes while copying a file?

The standard cp command has all you need to retain file permissions while copying. You can use the -p option of cp to preserve the mode, ownership, and timestamps of the file.

Does cut and paste retain permissions?

Permissions and Windows Fileshares When copying a file (copy/paste) or moving it (cut/paste) from one volume to another (e.g., from Collab to Home), the file will lose the original permissions it had before the copy/move.


1 Answers

If you look at the documentation for shutil, you'll immediately find the copy2 function, which is:

Identical to copy() except that copy2() also attempts to preserve all file metadata.

In recent versions of Python, there's a whole slew of functions to do bits and pieces of this separately—copy, copymode, copystat—but if you just want to copy everything, copy2 does everything possible.

As the warning at the top of the documentation says, "everything possible" doesn't mean everything, but it does include the dates and other attributes. In particular:

On Windows, file owners, ACLs and alternate data streams are not copied.

If you really need to include even that stuff, you will need to access the Win32 API (which is easiest to do via pywin32). But you don't.

like image 55
abarnert Avatar answered Sep 20 '22 17:09

abarnert