如何在Python3中复制文件?
先决条件:Shutil
当我们需要备份数据时,我们通常会制作该文件的副本。 Python支持文件处理并允许用户处理文件,即读写文件,以及许多其他文件处理选项,以对文件进行操作。在这里我们将学习如何使用 Python3 复制文件。
方法一:使用shutil库
Shutil 库包括一个方法调用 copyfile()。该方法有两个参数,一个是文件的源路径,另一个是文件的目标路径。下图包含一个文件及其路径。
句法:
copyfile(source_path,destination_path)
程序:
Python3
# copy a file using shutil.copyfile() method
import shutil
# path where original file is located
sourcePath = "c:\\SourceFolder\\gfg.txt"
# path were a copy of file is needed
destinationPath = "c:\\DestinationFolder\\gfgcopy.txt"
# call copyfile() method
shutil.copyfile(sourcePath, destinationPath)
Python3
# open source file in read mode
source = open("c:\\SourceFolder\\gfg.txt", "r")
# open destination file in write mode
dest = open("c:\\DestinationFolder\\gfgcopy.txt", "w")
# read first line
line = source.readline()
# read lines until reached EOF
while line:
# write line into destination file
dest.write(line)
# read another line
line = source.readline()
# close both files
source.close()
dest.close()
输出:
方法二:将文件的数据复制到另一个文件中
将一个文件的数据复制到另一个文件也可以创建文件备份。假设文件的数据如下:
程序:
蟒蛇3
# open source file in read mode
source = open("c:\\SourceFolder\\gfg.txt", "r")
# open destination file in write mode
dest = open("c:\\DestinationFolder\\gfgcopy.txt", "w")
# read first line
line = source.readline()
# read lines until reached EOF
while line:
# write line into destination file
dest.write(line)
# read another line
line = source.readline()
# close both files
source.close()
dest.close()
输出: