Python 复制或移动文件

Python 复制或移动文件

Python 复制或移动文件

在编程的过程中,我们经常需要在文件之间进行复制或移动操作。Python 提供了多种方式来实现这两个功能。本文将详细介绍如何使用 Python 复制或移动文件,并给出相应的例子和代码运行结果。

一、复制文件

1. 使用 shutil 模块

shutil 模块是 Python 的标准库之一,专门用于文件和目录的高级操作。它提供了 shutil.copy()shutil.copy2() 函数来实现文件的复制。

shutil.copy()

shutil.copy(src, dst) 函数将源文件 src 复制到目标文件或目录 dst。如果 dst 是一个目录,将会在目标目录下创建与源文件同名的新文件。

下面是一个例子,将当前工作目录下的文件 file.txt 复制到目标目录 dst_dir

import shutil

src_file = "file.txt"
dst_dir = "/path/to/destination"

shutil.copy(src_file, dst_dir)

shutil.copy2()

shutil.copy2(src, dst) 函数除了复制文件外,还会尽量保留文件的元数据(例如文件权限和时间戳)。

下面是一个例子,将当前工作目录下的文件 file.txt 复制到目标文件 dst_file 并保留元数据:

import shutil

src_file = "file.txt"
dst_file = "/path/to/destination/file.txt"

shutil.copy2(src_file, dst_file)

2. 使用 os 模块

os 模块是 Python 的标准库之一,提供了许多与操作系统交互的函数。其中包含了用于文件和目录操作的函数。

使用 os.system() 函数

os.system(command) 函数可以在命令行执行指定的命令。我们可以利用这个函数来调用操作系统提供的复制命令来复制文件。在 Windows 上,复制命令是 copy;在类 Unix 系统上,复制命令是 cp

下面是一个例子,在 Windows 上使用 copy 命令复制文件 file.txt 到目标目录 dst_dir

import os

src_file = "file.txt"
dst_dir = "/path/to/destination"

command = f"copy {src_file} {dst_dir}"
os.system(command)

使用 os.popen() 函数

os.popen(command, mode='r') 函数打开一个管道,返回一个文件对象。我们可以利用这个函数通过管道发送系统命令来复制文件。与 os.system() 不同,os.popen() 的返回值可以用于读取命令执行的输出结果。

下面是一个例子,在类 Unix 系统上使用 cp 命令复制文件 file.txt 到目标目录 dst_dir

import os

src_file = "file.txt"
dst_dir = "/path/to/destination"

command = f"cp {src_file} {dst_dir}"
output = os.popen(command).read()
print(output)

二、移动文件

1. 使用 shutil 模块

shutil 模块除了提供文件的复制函数,还提供了 shutil.move() 函数来实现文件的移动。

shutil.move(src, dst) 函数将源文件 src 移动到目标文件或目录 dst。如果 dst 是一个目录,将会在目标目录下创建与源文件同名的新文件。

下面是一个例子,将当前工作目录下的文件 file.txt 移动到目标目录 dst_dir

import shutil

src_file = "file.txt"
dst_dir = "/path/to/destination"

shutil.move(src_file, dst_dir)

2. 使用 os 模块

与复制文件类似,os 模块也提供了一些函数来实现文件的移动。

使用 os.rename() 函数

os.rename(src, dst) 函数将源文件 src 重命名为目标文件 dst。如果 dst 是一个存在的目录,src 将被移动到该目录下,并保持原有的文件名。

下面是一个例子,将当前工作目录下的文件 file.txt 移动到目标目录 dst_dir

import os

src_file = "file.txt"
dst_dir = "/path/to/destination"

dst_file = os.path.join(dst_dir, src_file)
os.rename(src_file, dst_file)

使用 shutil.move() 函数

shutil.move(src, dst) 函数不仅可以复制文件,还可以将文件移动到目标目录。

下面是一个例子,将当前工作目录下的文件 file.txt 移动到目标目录 dst_dir

import shutil

src_file = "file.txt"
dst_dir = "/path/to/destination"

shutil.move(src_file, dst_dir)

以上就是使用 Python 复制或移动文件的方法和示例代码。通过上述函数和方法,我们可以方便地在文件之间进行复制和移动,并且可以保留文件的元数据。在实际编程中,根据需要选择合适的方法来进行文件操作。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程