編輯:
我需要在 csv 檔案的特定列中存盤/添加/附加其他資訊,而不使用csv.DictReader.
如果我想跳過一列中的一行并且它是空的,我需要做什么?
例如:
示例 csv 檔案:
$ cat file.csv
"A","B","C","D","E"
"a1","b1","c1","d1","e1"
"a2","b2","c2","d2","e2"
"a2","b2","c2",,"e2"
代碼:
sample = ['dx;dy']
with(openfile.csv, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
headers = next(reader)
for row in reader:
#sample.append(to the column D)
輸出應如下所示:
$ cat file.csv
"A","B","C","D","E"
"a1","b1","c1","d1;dx;dy","e1"
"a2","b2","c2","d2;dx;dy","e2"
"a2","b2","c2",,"e2"
uj5u.com熱心網友回復:
由于您知道要附加到的列的標題,因此您可以headers在行中找到它的索引,然后修改每個row.
append_to_column = 'D'
separator = ';'
sample = ['dx;dy']
with open('file.csv', "r") as csvfile, open("outfile.csv", "w") as outfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
headers = next(reader)
writer = csv.writer(outfile, delimiter=',', quotechar='"')
col_index = headers.index(append_to_column)
for row in reader:
value = row[col_index]
new_value = value separator sample[0]
row[col_index] = new_value
writer.writerow(row)
這使:
A,B,C,D,E
a1,b1,c1,d1;dx;dy,e1
a2,b2,c2,d2;dx;dy,e2
請注意,此檔案沒有引號,因為它們不是必需的,因為欄位不包含任何逗號。如果你想強制csv.writer寫引號,你可以將quoting=csv.QUOTE_ALL引數添加到csv.writer()呼叫中,如下所示:writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
然后,你會得到:
"A","B","C","D","E"
"a1","b1","c1","d1;dx;dy","e1"
"a2","b2","c2","d2;dx;dy","e2"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/455915.html
標籤:Python python-3.x CSV
