Python 初学者练习:复制文件_python中的复制
在本教程中,您将学习如何使用 os、shutil 模块中提供的各种函数将文件和文件夹从一个位置复制到另一个位置。
在 Python 中使用 copy() 复制文件
复制文件可以使用 shutil 模块的 copy()方法。
import shutil
src_path=r"C:\temp1\abc.txt"
dst_path=r"C:\temp2\\"
shutil.copy(src_path,dst_path)
print('复制完毕!')
在 Python 中使用 copyfile() 复制文件
import shutil
src_path=r"C:\temp1\abc.txt"
dst_path=r"C:\temp2\abc2.txt"
shutil.copy(src_path,dst_path)
print('复制完毕!')
「copy()、copyfile()区别:」
copy()可以复制文件,还可以在复制时设置权限,而 copyfile() 只复制数据。
如果目标是目录,则 copy() 将复制文件,而 copyfile() 会失败。
复制文件夹中的所有文件
有时我们想将所有文件从一个文件夹复制到另一个文件夹。需要使用 os.listd()方法获取源文件夹中所有文件的列表。使用 for 循环遍历列表以获取各个文件名,使用 shutil.copy()方法复制文件。
import os
import shutil
src_path=r"C:\temp1\\"
dst_path=r"C:\temp2\\"
for file_name in os.listdir(src_path):
source=src_path+file_name
destination=dst_path+file_name
if os.path.isfile(source):
shutil.copy(source,destination)
print('复制完成:',file_name)
复制整个文件夹
需要复制整个文件夹,包括包含的所有文件和子文件夹。使用 shutil 模块的 copytree()方法以递归方式进行复制。
import shutil
src_path=r"C:\temp1"
dst_path=r"C:\temp2"
shutil.copytree(src_path, dst_path)
print("复制完成!")
使用 os.popen()方法复制文件
Python os 模块提供了可在不同操作系统中互操作的功能。
「在 Unix 上:」
import os
src_path=r"/Users/temp1"
dst_path=r"/Users/temp2"
os.popen('cp src_path\abc.txt dst_path\abc.txt')
print("复制完成!")
「windows」
import os
src_path=r"C:\temp1\\"
dst_path=r"C:\temp2\\"
os.popen('copy src_path\abc.txt dst_path\abc.txt')
print("复制完成!")
「文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!」