Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...