【问题标题】:Read CSV files in the same order as saved in my directory按照保存在我的目录中的相同顺序读取 CSV 文件
【发布时间】:2019-12-14 14:42:43
【问题描述】:

我的 CSV 文件在目录中按以下方式排序:

index_dc_20090131
index_dc_20090228
index_dc_20090331
index_dc_20090430
index_dc_20090531
index_dc_20090630

我正在通过以下方式阅读我的 csv 文件:

path = r'myDirectory' 
all_files = glob.glob(path + "/*.csv")
li = []
for filename in all_files:
    frame = pd.read_csv(filename, index_col = None, header = 0, sep = ";")
    li.append(frame)

我假设li 将按照与上述相同的顺序存储文件,但显然这是一个完全随机的顺序。显然,它与文件的名称或大小或它们包含的列数无关。

如何读取 CSV 文件以使它们与我的目录中的顺序相同?我想避免重命名我的文件。

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    Python 不会按任何特定顺序选择文件。如果你想让它们排序,你需要对它们进行排序:

    path = r'myDirectory' 
    all_files = glob.glob(path + "/*.csv")
    all_files.sort()
    li = []
    for filename in all_files:
        frame = pd.read_csv(filename, index_col = None, header = 0, sep = ";")
        li.append(frame)
    

    【讨论】:

      猜你喜欢
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2014-12-19
      • 2018-06-11
      • 2019-10-05
      • 2021-12-21
      相关资源
      最近更新 更多