目的:遍历某一路径下所有的文件,并将所有的文件移动到指定的路径
在日常工作中,我们经常需要整理文件,将它们从一个文件夹移动到另一个地方。为了更高效地完成这项任务,我们可以使用Python编写一个简单而实用的脚本。本文将介绍如何使用Python的os
和shutil
模块,遍历Windows文件夹并将所有文件(包括子文件夹中的文件)移动到指定的目标文件夹。
Talk is cheap ,show the code
import os
import shutil
def move_files(src_folder, dest_folder):
# 遍历源文件夹
for root, dirs, files in os.walk(src_folder):
for file in files:
src_path = os.path.join(root, file)
dest_path = os.path.join(dest_folder, file)
try:
shutil.move(src_path, dest_path)
print(f"Moved: {src_path} to {dest_path}")
except Exception as e:
print(f"Error moving {src_path}: {str(e)}")
if __name__ == "__main__":
# 设置源文件夹和目标文件夹路径
source_folder = r"C:\Path\To\Source\Folder"
destination_folder = r"C:\Path\To\Destination\Folder"
# 确保目标文件夹存在,如果不存在则创建
os.makedirs(destination_folder, exist_ok=True)
# 移动文件
move_files(source_folder, destination_folder)
1. 准备工作
在编写脚本之前,我们需要先准备好源文件夹和目标文件夹的路径。请确保你已经将source_folder
和destination_folder
变量的值更改为实际的文件夹路径。此外,为了避免错误,我们使用os.makedirs
函数确保目标文件夹存在,如果不存在则会创建。
source_folder = r"C:\Path\To\Source\Folder"
destination_folder = r"C:\Path\To\Destination\Folder"
# 确保目标文件夹存在,如果不存在则创建
os.makedirs(destination_folder, exist_ok=True)
2. 编写遍历并移动文件的脚本
接下来,我们将编写一个函数move_files
,该函数将遍历源文件夹中的所有文件和子文件夹,并将它们移动到目标文件夹中。我们使用os.walk
来实现递归遍历,并使用shutil.move
函数来移动文件。
def move_files(src_folder, dest_folder):
for root, dirs, files in os.walk(src_folder):
for file in files:
src_path = os.path.join(root, file)
dest_path = os.path.join(dest_folder, file)
try:
shutil.move(src_path, dest_path)
print(f"Moved: {src_path} to {dest_path}")
except Exception as e:
print(f"Error moving {src_path}: {str(e)}")
3. 执行脚本
最后,我们将脚本的执行部分放在if __name__ == "__main__":
块中,确保脚本只在直接运行时执行而不在导入时执行。
if __name__ == "__main__":
# 移动文件
move_files(source_folder, destination_folder)
4. 结论
这个简单而实用的Python脚本可以帮助我们快速整理文件,将它们从一个文件夹移动到另一个地方。在使用脚本之前,请确保备份重要数据,并仔细阅读代码以确保其符合您的需求。通过学习这个脚本,你将能够更好地利用Python进行文件操作,提高工作效率。