copy file, keep permissions and owner

guettli picture guettli · Nov 5, 2013 · Viewed 13.4k times · Source

The docs of shutil tells me:

Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) can’t copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs

How can I keep the file owner and group if I need to copy a file in python?

The process runs on linux as root.

Update: We don't use ACLs. We only need to keep the stuff which is preserved with tools like tar and rsync.

Answer

Thom Wiggers picture Thom Wiggers · Nov 12, 2013

You perhaps could use os.stat to get the guid and uid like in this answer and then reset the uid and guid after coping using os.chown.