【问题标题】:Python importing csv files within subfoldersPython在子文件夹中导入csv文件
【发布时间】:2021-07-14 12:19:00
【问题描述】:

有没有办法导入文件夹 1 中的所有文件?每个 csv 文件都包含在一个子文件夹中。下面是文件结构。

C:/downloads/folder1 > tree /F

C:.
│   tree
│
├───2020-06
│       test1.csv
│
├───2020-07
│       test2.csv
│
├───2020-08
│       test3.csv
│
├───2020-09
│       test4.csv

我知道下面的 glob 可以获取文件夹中的所有文件。但是这可以用于子文件夹吗?

import glob
import pandas as pd

# Get a list of all the csv files
csv_files = glob.____('*.csv')

# List comprehension that loads of all the files
dfs = [pd.read_csv(____) for ____ in ____]

# List comprehension that looks at the shape of all DataFrames
print(____)

【问题讨论】:

    标签: python jupyter glob


    【解决方案1】:

    使用glob.glob() 方法的recursive 关键字参数:

    glob.glob('**\\*.csv', recursive=True)
    

    【讨论】:

    • 有没有办法将文件路径列表导入数据框?
    • @IOIOIOIOIOIOI 你是说[pandas.read_csv(file) for file in glob('**\\*.csv', recursive=True)?
    【解决方案2】:

    您可以使用os.walk查找所有子文件夹并获取所需文件

    这是一个代码示例

    import os
    import pandas as pd
    
    path = '<Insert Path>'
    file_extension = '.csv'
    csv_file_list = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if name.endswith(file_extension):
                file_path = os.path.join(root, name)
                csv_file_list.append(file_path)
    
    dfs = [pd.read_csv(f) for f in csv_file_list]
    

    【讨论】:

    • 有没有办法将文件列表导入单独的数据帧?
    • 您在示例中使用的列表理解方法仅适用于文件。
    • 我在答案中添加了列表理解
    【解决方案3】:

    我在Kite's 网站上找到了这个,检查一下

    path = "./directory/src_folder"
    
    text_files = glob.glob(path + "/**/*.txt", recursive = True)
    
    print(text_files)
    OUTPUT
    ['./directory/src_folder/src_file.txt', './directory/src_folder/subdirectory/subdirectory_file.txt']
    

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 2013-02-19
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2014-03-29
      • 2023-02-02
      相关资源
      最近更新 更多