首页 > 解决方案 > 从多个文件夹中批量提取和重命名 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”

标签: python

解决方案


只需检查文件是否存在并增加一个计数器,直到文件名可用:

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

如果你想要一个后缀,而不是一个文件的前缀,你应该从扩展名中拆分名称,附加一个数字,然后再次加入。


推荐阅读