【问题标题】:Read csv data, then append text file with values at specific places读取 csv 数据,然后在特定位置附加带有值的文本文件
【发布时间】:2015-05-21 10:37:52
【问题描述】:

我刚开始使用 Python,并没有很好地掌握 Python 中使用的所有函数和方法。希望有人可以在这方面给我指点。 问:我正在尝试读取包含多行 x、y 和 z 数据的 CSV 文件。然后,我需要获取这些读取值并将它们替换到特定位置的文本文件中。
我可以使用 csv.reader 来读取文件,但我很难找到正确的函数来在我的文本文件中搜索和附加数据。

CSV 文件包含;

X  Y  Z

1 x1 y1 z1

2 x2 y2 z2

3 x3 y3 z3

文本文件包含:

This is first text line.
The data goes here x1 with y1 and z1
also goes here x2 wtih y2 and z2.

作为第一步,我在将数据写入新文本文件方面取得了一些进展:

import csv
testfile = open('Data.csv', "rb")
reader =  csv.reader(testfile)
rownum = 0
file=open("detdata.txt", "w")
for row in reader:
    # Save header row.
    if rownum == 0:
    *
    *

【问题讨论】:

  • 这里的主要问题是什么?请完成我的任务?
  • 文本的行号是否应该与 CSV 行号匹配,即第一行文本只会从第一行获取变量,从第二行获取第二行文本等,或者它们都是混合的整个文本?
  • @brunodesthuilliers:感谢您的及时回复。是的,csv 文件第 2 行 (x1, y1,..) 中的数字需要转到文本文件第 2 行中的特定位置。 csv 文件中的每个变量(一个值)都需要转到文本文件中预先分配的位置,该位置已经有一些默认值。

标签: python csv text append


【解决方案1】:

脑残、脆弱、低效且未经测试的解决方案:

source = open("/path/to/textfile.txt").read()
keys = ("x", "y", "z")
reader.next() # discard the headers row
for num, row in enumerate(reader, 1):
    for key, val in zip(keys, row):
        varname = "{0}{1}".format(key, num)
        source = source.replace(varname, val)

更好的解决方案是在文本文件中使用带有 Python 字符串格式化标记的模板字符串,即:

This is first text line.
The data goes here {x1} with {y1} and {z1}
also goes here {x2} wtih {y2} and {z2}.

然后在dict 中收集varname:values 对并使用str.format():

data = dict()
keys = ("x", "y", "z")
reader.next() # discard the headers row
for num, row in enumerate(reader, 1):
    for key, val in zip(keys, row):
        varname = "{0}{1}".format(key, num)
        data[varname] = val

source = open("/path/to/textfile.txt").read()
result = source.format(**data)

但请注意,如果文本中有占位符,而 dict 中没有匹配键,则会出现错误。

【讨论】:

  • 嗨,布鲁诺,感谢您对此提出的建议。 reader.next() 函数由于某种原因对我不起作用;(
猜你喜欢
  • 2017-10-22
  • 2019-08-04
  • 2014-08-07
  • 2021-03-15
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多