Images/zebra.png is the path to the image.Inside the Project folder, accessing the subfolders Images and Favorites is trivial: The parent folder has to be specified because otherwise, the code.py script would search inside the Scripts folder which has no other files except for the code file. In the case of the Scripts folder, this refers to the Project folder in which the Images and Favorites folders live. Let’s examine the paths to understand how they work. Here is how the code.py file looks in the Scripts folder from shutil import copyfile Here is an illustration of the folder structure:īecause the code file, the source file, and the destination all lie in different folders, you need to work with paths instead of file names. This is a program file that copies an image called zebra.png from Images to Favorites. Inside the Scripts folder, you have a file called code.py. ![]() ![]() Inside this folder, you have three subfolders called Scripts, Images, and Favorites. Let’s say you have a folder called Project. Let’s see a simple and demonstrative example. The path obviously depends entirely on your file setup. If you want to copy a file from one folder to another, you need to specify the path of the source and the destination. If this is the case, accessing the files with their names is not possible. More often than not your files are not going to be in the same folder. This is how easy it is to copy a file using Python. Here is the code: from shutil import copyfileĪfter running this piece of code, you should see a file called Example2.txt appear in the same folder: The example.py is a program that copies the file called Example1.txt to a new file called Example2.txt.īecause you are working in the same folder, you do not need to worry about the full paths of the files. Let’s start with a setup like this, where you have two files Example1.txt and example.py in the same folder on your computer: To understand how to copy a file in Python, you need to see an example. Real-Life Example of How to Copy a File with Python ![]() If it does, the file behind that path is overridden. If a file dst does not exist, a new file is created. This piece of code copies the contents of the file src to a destination file dst.īoth src and dst are strings that represent the names of the files (or rather, paths to the files). To copy a file in Python, use the shutil module’s copyfile() function.
0 Comments
Leave a Reply. |