【发布时间】: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