【问题标题】:Export specific CSV filename (eg: abc*.csv) from list of folders within a folder using python through looping method使用python通过循环方法从文件夹内的文件夹列表中导出特定的CSV文件名(例如:abc * .csv)
【发布时间】:2022-01-11 02:59:12
【问题描述】:

如何遍历文件夹中的多个文件夹并导出以例如“abc*.csv”开头的特定 CSV 文件名并将它们导出到新文件夹目录中。

尝试在堆栈溢出中搜索类似示例,但大多数示例是读取文件夹中的多个 CSV 文件并将它们组合到一个数据帧中。谢谢。

【问题讨论】:

  • 到目前为止你有没有尝试过?有什么代码可以分享吗?
  • 你自己尝试过什么?您遇到问题的哪一部分?遍历文件夹?在这些文件夹中获取 .csv 文件名?检查它们是否符合您需要的模式?将它们导出到其他地方?
  • 您没有找到解决方案,因为这是关于在文件夹中搜索文件,与 CSV 无关,只是它是您在文件夹中查找的文件类型的过滤器。
  • 此外,由于您正在处理文件,如果它们符合您的查找条件,您将把它们复制到新位置……

标签: python csv


【解决方案1】:
import os
import shutil

files = []
source_dir = ['./files/']
dest_dir = './export/'

# List all files from all directories within the path
while len(source_dir) > 0:
    for (dirpath, dirnames, filenames) in os.walk(source_dir.pop()):
        source_dir.extend(dirnames)
        files.extend(map(lambda n: os.path.join(
            *n), zip([dirpath] * len(filenames), filenames)))

# Loop thru files to copy/move the matching CSVs
for file in files:
    if file.startswith('abc') and file.endswith('.csv'):
        shutil.copy(file, dest_dir)
        # shutil.move(file, dest_dir)  # Use .move to move the file instead

如果你有这个文件结构:

files
├── dir1
│   ├── abc789.csv
│   └── abc789.txt
├── dir2
│   ├── abc098.csv
│   └── abc098.txt
└── dir3
    ├── abc456.csv
    └── subdir3
        ├── abc123.csv
        └── abc123.txt

只会导出匹配的文件:

$ ls export/
abc098.csv abc123.csv abc456.csv abc789.csv

【讨论】:

  • 谢谢先生!是的,问题描述正确。但是,当我运行上面的代码时,我得到了这个错误 "str' object has no attribute 'pop'" 。请帮忙。谢谢。
  • 您需要将源定义为像source_dir = ['./files/'] 这样的列表,而不是字符串,因为子目录会添加到该列表中
  • 是的,我已将它们定义为我的源目录和新目录,但显示错误“str' object has no attribute 'pop'。谢谢
  • @JimmyWong 再次,如果它显示"str' object has no attribute 'pop',则表示您将源目录设置为source_dir = './files/' 而不是source_dir = ['./files/']
猜你喜欢
  • 2021-06-27
  • 2020-12-12
  • 2019-06-13
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多