「Python」文件操作 - 基于 shutil 实现移动、复制以及重命名

在工程中,常会遇到需要对于文件批量操作的情况,比如对文件进行移动、复制以及重命名等操作。本文介绍基于 Python shutil 包实现对文件的移动、复制以及重命名等操作。

shutil 主要针对文件进行拷贝、删除、移动和压缩。之前在[[读取文件夹文件并且移动]]中介绍过使用 shutil 进行深度模型训练过程中的数据集的移动。

1. 基础函数介绍

  • 复制函数 shutil.copy()
shutil.copy(src, dst, *, follow_symlinks=True)

这分为两种情况,当 dst 为文件路径时候,将文件 src 复制到 dst 所在文件夹,并将重命名为 dst 对应文件名;当 dst 为文件夹时候,将文件 src 复制到 dst 文件夹下。

  • 移动/重命名函数 shutil.move()
shutil.move(src, dst, copy_function=copy2)

这分为两种情况,当 dst 为文件路径时候,将文件 src 移动到 dst 所在文件夹,并将重命名为 dst 对应文件名;当 dst 为文件夹时候,将文件 src 移动到 dst 文件夹下。

2. 示例 demo

以下列的文件目录情况作为 demo 的演示。

.
├── folder1
│   └── file1.txt
└── folder2
    └── file2.txt
  • file1.txt 复制到 folder2
import shutil

shutil.copy('./folder1/file1.txt', './folder2')
  • ./folder2/file1.txt 重命名为 ./folder2/file3.txt
import shutil

shutil.copy('./folder2/file1.txt', './folder2/file3.txt')
  • file3.txt 移动到 folder1
import shutil

shutil.copy('./folder2/file3.txt', './folder1')
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
文件重命名是指对文件名进行更改,可以根据需要修改文件名的基础格式、添加前缀或后缀、删除特定字符等。在Python中,我们可以使用os库或shutil库来实现文件重命名的功能。 下面是几种常见的文件重命名方法: 方法1:使用os库的rename方法 ```python import os def rename_files(path): # 遍历文件夹内的所有文件 for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): # 对文件进行重命名操作 new_name = "new_" + file # 根据需要设置新的文件名格式 os.rename(os.path.join(path, file), os.path.join(path, new_name)) # 调用函数,传入文件夹路径 rename_files("文件夹路径") ``` 方法2:使用shutil库的copy和move方法 ```python import shutil def rename_files(path_old, path_new): # 遍历原数据文件夹内的所有文件 for file in os.listdir(path_old): if os.path.isfile(os.path.join(path_old, file)): # 对文件进行重命名操作 new_name = "new_" + file # 根据需要设置新的文件名格式 shutil.copy(os.path.join(path_old, file), os.path.join(path_new, new_name)) # 复制文件到新的文件夹 # 或者使用shutil.move方法,直接移动文件到新的文件夹并重命名 #shutil.move(os.path.join(path_old, file), os.path.join(path_new, new_name)) # 调用函数,传入原数据文件夹路径和重命名后的文件夹路径 rename_files("原数据文件夹路径", "重命名后的文件夹路径") ``` 方法3:使用随机命名方法 ```python import os import random import string def rename_files(path): # 遍历文件夹内的所有文件 for file in os.listdir(path): if os.path.isfile(os.path.join(path, file)): # 对文件进行随机命名操作 name = file.split('.')[0] suffix = file.split('.')[1] salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) # 生成8位由英文字符和数字组成的随机字符串 new_name = name.replace(name, salt) + '.' + suffix os.rename(os.path.join(path, file), os.path.join(path, new_name)) # 调用函数,传入文件夹路径 rename_files("文件夹路径") ``` 以上是文件重命名的几种常见方法,你可以根据具体需求选择适合的方法。如果有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值