【问题标题】:Can ConfigParser be used to read sections containing column data?ConfigParser 可以用来读取包含列数据的部分吗?
【发布时间】:2022-01-10 05:29:08
【问题描述】:

我有大型输入文件,格式为:

[A11N]
#       label     value              error          calculated
         0     1.43262100e+06    2.12071439e+04    1.43261891e+06
         1     3.05578100e+05    2.12071439e+04    3.26592619e+05
         2     3.95689900e+05    2.12071439e+04    3.84788096e+05
         3     4.90816000e+05    2.12071439e+04    4.64785030e+05
         2     5.42676800e+05    2.12071439e+04    5.42395048e+05
[B12N]
#       label     value              error          calculated
         0     1.43262100e+06    2.12071439e+04    1.43261891e+06
         1     3.05578100e+05    2.12071439e+04    3.26592619e+05
         2     3.95689900e+05    2.12071439e+04    3.84788096e+05
         3     4.90816000e+05    2.12071439e+04    4.64785030e+05
         2     5.42676800e+05    2.12071439e+04    5.42395048e+05
[C13N]
#       label     value              error          calculated
         0     1.43262100e+06    2.12071439e+04    1.43261891e+06
         1     3.05578100e+05    2.12071439e+04    3.26592619e+05
         2     3.95689900e+05    2.12071439e+04    3.84788096e+05
         3     4.90816000e+05    2.12071439e+04    4.64785030e+05
         2     5.42676800e+05    2.12071439e+04    5.42395048e+05

请注意,标签列将包含重复值,因此我不能简单地在“标签”和“值”列之间添加一个“=”符号。我通常使用 'genfromtxt' 读取这样的列数据,但这与部分标签不同。

可以让 ConfigParser.read 来处理这样的部分吗?还是逐行处理是解析输入文件的唯一方法?

【问题讨论】:

  • 我会将该文件按“类别”([A11N] 等)分割成块,然后使用csv 库处理数据。

标签: python csv file-io configparser


【解决方案1】:

首先遍历文件,使用“部分”([A11N] 等)作为字典键,然后将剩余的行作为值推送到列表中。

完成后,您可以遍历字典,将列表处理为 csv:

import csv

csvdata = {}
with open('data.txt', newline='') as csvfile:
  category = ''
  for line in csvfile.readlines():
    line = line.strip()
    if line.startswith('['):
      category = line
      csvdata[category] = []
    else:
      csvdata[category].append(line)

for cat, row in csvdata.items():
  # Print the section name
  print(cat)
  reader = csv.reader(row, delimiter=' ')
  for data in reader:
    # Print the list of row fields
    print(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2012-12-17
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多