python - 从多个文件夹中批量提取和重命名 csv 文件 - Python
问题描述
我在一个目录中有 350 个文件夹,它们都包含两个名为“证书”和“建议”的 csv 文件。我想将每个“certificates.csv”文件移动到一个新文件夹中,但还要在此过程中更改这些 .csv 文件的名称,添加一个索引号作为后缀,这样它们就不会相互覆盖,即“certificates1”、“证书2"...."证书350"等。
尝试将所有文件移动到一个文件夹中时,我设法做到了这一点:
import os
import shutil
src_dir = "C:/IN"
dst_dir = "C:/OUT"
for root, dirs, files in os.walk(src_dir):
for f in files:
if f.endswith('.csv'):
shutil.copy(os.path.join(root,f), dst_dir)
但所做的只是循环遍历在此过程中相互覆盖的文件,因为它们都具有相同的名称 - “certificates.csv”
解决方案
只需检查文件是否存在并增加一个计数器,直到文件名可用:
for root, dirs, files in os.walk(src_dir):
for f in files:
if f.endswith('.csv'):
index = 0
while True:
new_path = os.path.join(dst_dir, str(index) + f)
if os.path.isfile(new_path):
index += 1
continue
shutil.copy(os.path.join(root, f), new_path)
break
如果你想要一个后缀,而不是一个文件的前缀,你应该从扩展名中拆分名称,附加一个数字,然后再次加入。
推荐阅读
- angular - 离子应用中的循环依赖
- node.js - Javascript Promises 和 map 函数
- oracle - 当查询返回值并且没有“EXCEPTION WHEN NO_DATA_FOUND THEN”时传递数据(Oracle 11g)
- c# - 使用 C# 将文件上传到 azure 文件存储使目录中的所有其余文件长度为 0
- c# - CultureInfo 对大名称(字符串)的“奇怪”响应
- mongodb - 任何云功能都可以有英国 IP 地址吗?
- python - 远程连接到 MongoDB 数据库而不以明文形式存储密码
- java - 在 sbt 应用程序中自定义 ForkJoinPool
- c# - 升级到 ASP.NET Core 2.2 后如何配置 Azure 日志记录
- python - 在列表的字典中切换键和值