現在、単一のデータ項目を CSV の行に追加しようとしていますが、正しいフィールド値の下に追加し続けます。フロートを使用する必要がありますか? ここが本当に不安。どんな助けでも大歓迎です。このコードは基本的に、現在のデータを見逃してから、行の空の csv 列に変数を挿入しようとしています。
writer.writerow([""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[cweight])
現在、単一のデータ項目を CSV の行に追加しようとしていますが、正しいフィールド値の下に追加し続けます。フロートを使用する必要がありますか? ここが本当に不安。どんな助けでも大歓迎です。このコードは基本的に、現在のデータを見逃してから、行の空の csv 列に変数を挿入しようとしています。
writer.writerow([""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[""]+[cweight])
あなたの問題を正しく理解していれば、次のタイプの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)