copy a file in python

One way to copy a file in Python is to use the shutil module, which provides a higher level interface to file operations. Here is an example code snippet that demonstrates how to use the shutil.copyfile() function to copy a file:

main.py
import shutil

# path to input and output files
src_file = '/path/to/source/file.txt'
dst_file = '/path/to/destination/file.txt'

# perform copy operation
shutil.copyfile(src_file, dst_file)
191 chars
9 lines

Alternatively, you could use the os module to perform the file copy operation using open() and write() functions as shown below:

main.py
import os

# path to input and output files
src_file = '/path/to/source/file.txt'
dst_file = '/path/to/destination/file.txt'

# perform copy operation
with open(src_file, 'rb') as fsrc:
    with open(dst_file, 'wb') as fdst:
        fdst.write(fsrc.read())
257 chars
11 lines

Note that using shutil module is a preferred way to handle file copying, as it provides additional error checking and reporting compared to the low level os module.

gistlibby LogSnag