Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Copy Files in Python with shutil.copy() and shutil.copystat()

Python File‑Copying Basics

Python’s shutil module offers straightforward functions for copying files and preserving metadata. The two primary utilities are shutil.copy() and shutil.copystat().

copy(src, dst)

Copies the file located at src to the destination dst. The file contents are duplicated, but file permissions and timestamps are not preserved.

copystat(src, dst)

Copies file metadata—including permissions, timestamps, and other OS‑specific attributes—from src to dst. It must be called after a successful copy() to replicate the full file state.

Step‑by‑Step Example

  1. Locate the source file
    Confirm that guru99.txt exists in the current working directory and retrieve its absolute path.

Copy Files in Python with shutil.copy() and shutil.copystat()

import os
from os import path

src_path = path.realpath("guru99.txt")
print("Source:", src_path)
  1. Create a backup name
    Append .bak to the original filename to form the destination path.
dst_path = src_path + ".bak"
print("Destination:", dst_path)
  1. Copy the file contents
    Use shutil.copy() to duplicate the file data.
import shutil
shutil.copy(src_path, dst_path)
  1. Copy the metadata
    After the content copy, replicate the original file’s permissions and timestamps.
shutil.copystat(src_path, dst_path)
  1. Verify the copy
    Use the os.path.getmtime() function to display the last‑modified time of the backup file.
import datetime
mod_time = path.getmtime(dst_path)
print("Last modified:", datetime.datetime.fromtimestamp(mod_time))

Running the script will create guru99.txt.bak in the same directory, complete with the same permissions and timestamps as the original.

Practical Tips

Summary

Python

  1. Python File I/O: Mastering File Operations, Reading, Writing, and Management
  2. Python len(): A Practical Guide to Measuring Object Lengths
  3. Master Python's String.find() Method: Syntax, Examples & Alternatives
  4. Understanding Python's Main Function: A Practical Guide to def main()
  5. Checking File and Directory Existence in Python – A Practical Guide
  6. How to Rename Files and Directories in Python with os.rename() – Step-by-Step Guide
  7. Creating ZIP Archives in Python: From Full Directory to Custom File Selection
  8. Mastering Python’s readline() – Efficient Line‑by‑Line File Reading
  9. How to Read and Write CSV Files in Python: A Comprehensive Guide
  10. Python File I/O: Mastering Input and Output Operations