【问题标题】:Writing to a row in a CSV with data already in the row apart from one column in that row and inserting data into that empty coloumn写入 CSV 中的一行,其中除了该行中的一列之外,该行中已有数据,并将数据插入该空列
【发布时间】:2015-01-15 20:05:04
【问题描述】:

当前尝试将单个数据项添加到 CSV 中的一行,但它一直将其添加到正确的字段值下方。我需要使用浮点数吗?这里真的不确定。任何帮助,将不胜感激。 这段代码基本上是想漏掉当前数据,然后在行中的空 csv 列中插入一个变量。

writer.writerow([""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[cweight])

【问题讨论】:

  • 我认为您需要提供更多背景信息。如果我要结束问题,我会投票结束这个问题,因为“不清楚你在问什么”。

标签: csv floating-point row string writing


【解决方案1】:

如果我正确理解您的问题,您有以下类型的 csv 数据

Field1, Field2, Field3, Field4
Value1,Value2,,Value4

并且您想使用 .writerow() 函数进行以下操作

Field1, Field2, Field3, Field4
Value1,Value2,Value3,Value4

但是相反,你的结果一直是

Field1, Field2, Field3, Field4
Value1,Value2,,Value4
,,Value3,

如果是这种情况,那么您可以使用 csv.reader 读取值,将其分配到正确的索引位置,然后使用 csv.writer 将结果写入新文件。

import csv

# Open the input and output csv files
with open(example_input.csv, "rb") as csvFileInput:
    with open(example_output.csv, "wb") as csvFileOutput:

# Set the reader on the input csv
# Set the writer on the output csv
    reader = csv.reader(csvFileInput)
    writer = csv.writer(csvFileOutput)

# read the first row and assign the field names from the reader to a variable
    fields = reader.next()

# write the field names to the new output csv.
    writer.writerow(fields)

# Read the next line with data values from the input csv
    row = reader.next()

# read the index position of the empty (or replaceable) data value from input csv
# Assign the row value to a new value
# Write the new row to the output csv
    row[2] = 'Value3'
    writer.writerow(row)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多