Python遍历Windows文件夹并移动文件

目的:遍历某一路径下所有的文件,并将所有的文件移动到指定的路径

在日常工作中,我们经常需要整理文件,将它们从一个文件夹移动到另一个地方。为了更高效地完成这项任务,我们可以使用Python编写一个简单而实用的脚本。本文将介绍如何使用Python的osshutil模块,遍历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_folderdestination_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进行文件操作,提高工作效率。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值