利用Python复制文件的9种方法总结

您所在的位置:网站首页 python随机加减法 利用Python复制文件的9种方法总结

利用Python复制文件的9种方法总结

2024-07-17 15:08| 来源: 网络整理| 查看: 265

标题:利用Python复制文件的9种方法总结

首先,需要明确Python中文件复制的基本方法:使用shutil模块中的copy()方法。下面开始介绍“利用Python复制文件的9种方法总结”:

1. 使用shutil模块中的copy()方法

可以通过Python的shutil模块中的copy()方法对文件进行复制。该方法接受两个参数,一个是源文件的路径,另一个是目标文件的路径。示例代码如下:

import shutil src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' shutil.copy(src_file, dst_file) 2. 使用shutil模块中的copy2()方法

和copy()方法相似,copy2()方法同样可以实现文件复制的功能。但是,copy2()方法会复制源文件的所有属性,如文件的创建时间、最后修改时间等,不会更改目标文件的属性。

import shutil src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' shutil.copy2(src_file, dst_file) 3. 使用os模块中的system()方法

可以使用Python的os模块中的system()方法对文件进行复制。这种方法使用了shell命令,可以复制文件或目录。

import os src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' os.system('cp {} {}'.format(src_file, dst_file)) 4. 使用os模块中的popen()方法

和system()方法类似,popen()方法同样使用了shell命令,可以复制文件或目录。但是,popen()方法会返回一个文件对象,可以读取命令输出。

import os src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' f = os.popen('cp {} {}'.format(src_file, dst_file)) print(f.read()) 5. 使用subprocess模块中的run()方法

subprocess模块可以运行外部命令,并且可以获取输出。通过使用该模块中的run()方法,可以实现文件的复制。

import subprocess src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' subprocess.run(['cp', src_file, dst_file]) 6. 使用subprocess模块中的Popen()方法

Popen()方法用于运行外部命令,并可读写子进程的输入输出。可以使用该方法实现文件的复制。

import subprocess src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' p = subprocess.Popen(['cp', src_file, dst_file]) p.wait() 7. 使用os模块中的mmap()方法

os模块中的mmap()方法将文件映射到内存中,这样就可以操作文件的内容。可以通过mmap()方法实现文件的复制。

import os src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' # 将源文件和目标文件都映射到内存中 with open(src_file, 'r') as fsrc: with open(dst_file, 'w') as fdst: data = mmap.mmap(fsrc.fileno(), 0, prot=mmap.PROT_READ) fdst.write(data.read()) 8. 使用os模块中的sendfile()方法

os模块中的sendfile()方法用于文件和文件描述符之间的传输,并且在复制文件时非常快速。

import os src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt' with open(src_file, 'rb') as fsrc: with open(dst_file, 'wb') as fdst: os.sendfile(fdst.fileno(), fsrc.fileno()) 9. 使用tarfile模块和gzip模块

可以使用tarfile模块和gzip模块将文件打包成tar.gz压缩包,并将其解压缩到目标路径。从而实现文件的复制。

import tarfile import gzip src_file = '/path/to/source/file.txt' dst_file = '/path/to/destination/file.txt.tar.gz' # 将源文件打包成tar.gz压缩包 with tarfile.open(dst_file, 'w:gz') as tar: tar.add(src_file) # 将tar.gz压缩包解压到目标路径 with gzip.open(dst_file, 'rb') as fsrc: with open('/path/to/destination/file.txt', 'wb') as fdst: fdst.write(fsrc.read())

以上就是“利用Python复制文件的9种方法总结”完整攻略的介绍。其中,示例代码中的文件路径需要根据实际情况进行修改。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用Python复制文件的9种方法总结 - Python技术站



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3