This article describes how to use python
The file / Folder for copying .
Last Modified: 2022 / 7 / 3
There are several third-party libraries available for copying files
os
shutil
Several advanced functions are provided to support file copying and deletion .pathlib
from Python 3.4
Start , You can use pathlib
modular , It provides classes that represent object-oriented file system paths .Path.write_bytes()
function , It opens the file pointed to in byte mode , Write data to , Then close the file . There will be no exchange of file metadata .Examples can be found here 1
src = 'A.py'
dst = 'B.py'
with open(src, 'r') as f:
data = f.read()
with open(dst, 'w') as f:
f.write(data)
# It can be in reading mode (`r`) Open the source file and put its contents in write mode (`w`) Open the target file .
# Write mode opens the file for writing after truncating the file , If the file does not exist, create one .
Examples can be found here 2
os.system('copy A B')
os.system('cp A.py Folder/B.py')
# Will be under the current path of A.py Copy to Folder Save as next B.py
Examples can be found here 2’ 1
copy2
If dst
It's a file name ,src
Content and file metadata are copied ; dst
Is an existing file , It will be src
File replacement .dst
Specify a directory , We will copy src
File to directory dst
. If a file with the same name already exists in the destination , It will be overwritten .copy2
You can accept the target directory path and copy the file metadata .copy()
Same as copy2
Functional equivalent , But it cannot retain metadata .copyfile
If dst
It's a file name ,src
The content will be copied, but the metadata will not be copied .dst
Is an existing file , It will be src
File replacement .shutil.copy2(src, dst, *, follow_symlinks=True)
src = 'A.py'
dst = 'Folder'
# dst = 'Folder/B.py'
shutil.copy2(src=src, dst=dst)
# Will be under the current path of A.py copy to Folder or Folder Save as next B.py
shutil.copyfile(src, dst, *, follow_symlinks=True)
src = 'A.py'
dst = 'Folder/B.py'
shutil.copyfile(src=src, dst=dst)
# Will be under the current path of A.py copy to Folder Save as next B.py, Do not copy metadata .
# however , If it already exists , It will overwrite the target file .
Examples can be found here 1
src = pathlib.Path('A.py')
dst = pathlib.Path('Folder/B.py')
dst.write_bytes(src.read_bytes())
%todo:
use Python Nine ways to copy files
stay Python Copy files from ︎︎︎
Python Two simple ways to copy files in ︎︎