【发布时间】:2020-02-11 10:46:03
【问题描述】:
我有一个 csv 文件的文件夹。每个 csv 文件都是一本字典。我想将这些 csv 中的每一个读回字典,并将文件名作为字典名称。
例如。我的文件夹“CSV-Dictionaries”有许多 csv 文件 'file1.csv' 'file2.csv' 等我想读取这些单独的文件,以便它们的字典名称是 file1 和 file2。
这就是我创建 csvs 的方式。但现在我想使用 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")
【问题讨论】:
-
像
{fname: open(fname) for fname in os.listdir('CSVFolder') if fname.endswith('.csv')这样的东西会构造字典 -
直接将文件字典放入主字典。无需创建中间名称。
-
你说csvs上有字典我没明白,你的意思是什么?
-
也不清楚如果你想要文件对象或dict键处的文件内容,我建议文件对象,并将文件读取推迟到尽可能晚
标签: python pandas csv dictionary jupyter