python移动文件
在 Python 中,可以使用 shutil
模块来实现将文件夹下的指定文件移动到另一个文件夹下并替换。以下是一个示例代码,假设要将文件夹 source_folder
中的名为 file_to_move.txt
的文件移动到文件夹 destination_folder
中,并替换同名文件:
import os
import shutil
# 源文件夹路径
source_folder = '/path/to/source_folder'
# 目标文件夹路径
destination_folder = '/path/to/destination_folder'
# 要移动的文件名
file_to_move = 'file_to_move.txt'
# 构造文件的完整路径
source_file_path = os.path.join(source_folder, file_to_move)
destination_file_path = os.path.join(destination_folder, file_to_move)
# 判断源文件是否存在
if os.path.exists(source_file_path):
# 判断目标文件是否存在,如果存在则先删除
if os.path.exists(destination_file_path):
os.remove(destination_file_path)
# 移动文件到目标文件夹
shutil.move(source_file_path, destination_folder)
print(f"文件 '{file_to_move}' 移动成功")
else:
print(f"文件 '{file_to_move}' 不存在")
在上面的示例代码中,首先使用 os.path.join
函数构造源文件和目标文件的完整路径,然后使用 os.path.exists
函数判断源文件是否存在。如果源文件存在,则使用 os.remove
函数删除目标文件(如果存在的话),然后使用 shutil.move
函数将文件移动到目标文件夹。如果源文件不存在,则打印相应的提示信息。
请根据实际情况替换 source_folder
、destination_folder
和 file_to_move
的值,并确保程序有足够的权限来进行文件操作。