How to Copy a File in Python

American bald eagle over body of water

To copy a file using Python, use the shutil module’s copyfile() function:

from shutil import copyfile

copyfile(src, dst)

This copies the contents of the file src to a destination file dst. Both src and dst are strings that represent the names of the files (or paths to the files).

If dst does not exist, a new file is created. If it does, the file is overridden.

Real-Life Example of How to Copy a File with Python

Let’s say you have a setup like this:

The example.py is the program you want to use to copy the contents of the file Example1.txt. More specifically, you want to copy the contents to a new file called Example2.txt into the same folder.

As you’re working in the same folder, you don’t need to worry about paths. All you need is the names of the files.

So here is the code for you to copy contents of Example1.txt into a new file called Example2.txt:

from shutil import copyfile

src = 'Example1.txt'
dst = 'Example2.txt'

copyfile(src, dst)

After running this piece of code, you should see a file called Example2.txt appear in the same folder:

Conclusion

To copy a file using Python, use the shutil module’s copyfile() function:

from shutil import copyfile

copyfile(src, dst)

Where src is the path of the file to be copied (string) and dst the destination file’s path as a string.

Thanks for reading. Happy coding!

Further Reading

How to Read a Text File in Python

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *