I have save a figure in folder Dist with .png extension. Now in a for loop I want to implement a condition that if i<3 move or copy a certain figure from one folder to other. How can I do that in python?
Asked
Active
Viewed 588 times
1 Answers
0
Here is two methods of how you can copy a file to another folder:
For example if we have this tree directory:
.
├── destination # destination directory
├── moving.py # script that copies files
└── test.png # file to be copied
moving.py:
import os
import shutil
# Method 1
def copy_file(filename: str, destination: str):
"""Copy file to destination using shutil package
:param: filename is the file name path
:param: destination is the destination path
"""
shutil.copy(filename, destination)
# Method 2
def copy_file2(filename: str, destination: str):
"""Copy file to destination"""
data = b''
# Read the file in binary mode
with open(filename, 'rb') as f:
data = f.read()
# Write the file in binary mode
with open(os.path.join(destination, filename), 'wb') as f:
f.write(data)
# Example
filename = 'test.png'
destination = 'destination'
copy_file(filename, destination)
# copy_file2(filename, destination)
Both methods will copy the file to the new destination path and it'll keep the original name of the copied file.
Bonus: For more informations about shutil.copy()
function i recommend you reading the official documentation

Chiheb Nexus
- 9,104
- 4
- 30
- 43