将许多csvs的文件夹读入字典,每个字典的名称都是文件名



我有一个csv文件的文件夹。每个csv文件都是一个字典。我想将这些csv中的每一个读回字典中,文件名作为字典名称。

例如。我的文件夹"CSV词典"有很多csv文件 "文件1.csv"文件2.csv"等。我想读取这些单独的文件,以便它们的字典名称是 file1 和 file2。

这就是我创建 csv 的方式。但是现在我想使用 for 循环来阅读它们。

#dictionaries o f data
file1 = {'item11':1, 'item12': 2}
file2 = {'item21':3, 'item22': 4}
#dictionary of the data dictionaries with names
dicts = {'file1' : file1, 'file2' : file2}
#use pandas to make a dataframe and the write data frame to csv
for a_dict in dicts:
pd.DataFrame.from_dict(dicts[a_dict], orient="index", columns=['value']).to_csv("~/Downloads/"+a_dict+".csv", index_label="key")

您可以使用os.listdir(path_to_dir)获取文件夹中所有文件的列表,然后迭代该目录中的每个文件,将其打开并将名称保存为您描述的键。代码可能如下所示;

import os
import pandas as pd
def read_in_files_and_save_to_dict(folder_path):
csv_dict = {}
for filename in os.listdir(folder_path):
filename_path = f`{folder_path}/{filename}`
csv_dict[filename] = pd.read_csv(filename_path).to_dict()

相关内容

最新更新