28

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.

Community
  • 1
  • 1
Insert Text Here
  • 301
  • 1
  • 3
  • 5

1 Answers1

53

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 1
    If you read the docs carefully, you'll notice that `copy2` was intended to be equivalent to `cp -p` (which is what you wanted), but it actually can't emulate that on Windows (because of the file ownership problem), so instead they say that it copies "everything possible" and document what that means. Anyway, for your use case, it doesn't matter, but future readers might be mislead, so I edited the answer. – abarnert Jul 16 '13 at 19:27
  • It might be relevant. I am working on a forensics tool (that will allow me to copy files from one dirrectory to another). – Insert Text Here Jul 16 '13 at 19:45
  • @InsertTextHere, for forensics it's inacceptable to lose any portion of (meta)data, which is inevitable if you rely on such mechanisms. For example, it's possible for criminal to store data behind the end of file (till the end of cluster), and your forensics tool will miss it. Consider inspecting disk snapshot. – toriningen Jul 22 '13 at 23:15
  • 2
    Normally for forensics you'll want to copy the entire drive (not just the filesystem, or even just the partition—it's very easy to put data in unmapped parts of the drive) first and keep references to the source of each file and its metadata on the (signed and timestamped) copy. There's really no way to do that in a cross-platform way—especially if you suspect data may be hidden at the ATA/SCSI/etc. level. But anyway, `copy2` is probably sufficient to make a working copy that you can scan, as long as you can go back and get the relevant information once you've found what you're seeking. – abarnert Jul 31 '13 at 15:46
  • and `copytree` does it for folders. – Yvon Sep 11 '19 at 03:32