【问题标题】:Creating multiple dictionaries with parts of the file name as keys and content of the file as values创建多个字典,其中部分文件名作为键,文件内容作为值
【发布时间】:2021-07-12 14:45:54
【问题描述】:

我有许多 CSV 文件,每个文件名为 file1_OUT.csv、file2_OUT.csv [...] file52_OUT.csv 等。 csv 文件的内容如下所示:

| header1    | header2 |
| ---------- | ------- |
| 0.0000E+00 | ax      |
| 1.0000E+00 | ay      |
| 2.0000E+02 | bx      |
| 3.0000E+03 | by      |
| 4.0000E+03 | cx      |
| 4.0000E+01 | cy      |
| 0.0000E+00 | dx      |
| 0.0000E+00 | dy      |

对于每个文件,我想创建 8 个字典(ax、ay、bx、by、cx、cy、dx、dy),它们应该如下所示:

ax = {'file1': 0.0000E+00, 'file2': 5.0000E+00, 'file3': 2.0000E+00 ... }
ay = {'file1': 1.0000E+00, 'file2': 0.0000E+00, 'file3': 3.0000E+00 ... }
bx = {...}
by = {...}
... 

字典中的数字来自名为 header1 的列。

我对 python 很陌生,但我设法使用这段代码提取了 ax、ay 等的值:

import os, re, csv, glob
import pandas as pd 
import numpy as np
from pathlib import Path
from os import listdir
    
for file in Path(directory).glob('*_OUT.csv'):   
        with open(file, mode='r') as inp:
            ax = df['header1'][0]
            ay = df['header1'][1]
            bx = df['header1'][2]
            by = df['header1'][3]
            cx = df['header1'][4]
            cy = df['header1'][5]
            dx = df['header1'][6]
            dy = df['header1'][7]
            print(ax, ay, bx, by, cx, cy, dx, dy)

不幸的是,对于每个文件,srings 都被称为 ax,ay...,我猜它们在每次迭代中都被过度覆盖了。

此外,我还可以使用这段代码将文件名提取到一个列表中:

files_dir =  listdir(directory)
new_list = []
for names in files_dir:
    if names.endswith("_OUT.csv"):
        new_list.append(names.strip('.csv'))
print(new_list)

我不确定我的尝试有多大用处,因为我无法将 ax、ay、bx... 字符串与包含文件名的列表和字典结合起来(即我的输入 csv 文件的第二列) .有人有更好的主意吗?

【问题讨论】:

  • 我建议将所有这些 csv 文件导入为 SQLite 表

标签: python csv dictionary


【解决方案1】:

假设您的 python 脚本与您的 csv 文件位于同一文件目录中,您应该能够执行以下操作 - 这将返回一个嵌套字典结构,在每种情况下都以“header2”作为键。

import csv
import os

# gets current working directory of the python file - if neccessary, hard type the directory with the CSVs and replace cwd below
cwd = os.getcwd()

# list comprehension to build list of target CSV files in directory
target_files = [file for file in os.listdir(cwd) if file.endswith('csv')]

# create output dictionary
file_summaries = {}

# loop over files in target list
for filename in target_files:

    # open each file
    with open(filename, 'r') as file_in:
        # pass file to built-in csv.DictReader - returns data in list of dictionaries [{}, {}]
        file_data = csv.DictReader(file_in)

        # loop over each files' data - and set default info into file summary object
        for row in file_data:
            
            file_summaries.setdefault(row['header2'], {})
            file_summaries[row['header2']].setdefault(filename, row['header1'])


# display result
print(file_summaries)

【讨论】:

  • 感谢您的回答!您发送的代码似乎运行没有错误,但不幸的是它只创建了一个空字典。
  • 我猜你没有循环遍历任何文件? print(target_files) 以确认您实际上正在处理/打开任何数据。
  • 现在效果很好:) 非常感谢!我使用您建议的代码创建了嵌套字典。稍后在我的代码中,我只使用“file_summaries.pop”来处理数据,即 ax、ay、bx、by 等。
  • 无需使用 pop - Id 用于标头,file_summaries.items() 中的信息:// 无论如何处理标头,信息 - 如果有用,请考虑接受答案。
猜你喜欢
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 2022-11-12
相关资源
最近更新 更多