我正在嘗試使用 csv 模塊將每個欄位值括在雙引號中。但這里的技巧是我們在需要跳過的值之間確實有逗號。這是我用來將值括在引號中的代碼段。
資料:
col1,col2
first row,This section of the badge focuses on Communications
second row,Feedback has partnered with team members, leaders, and executives receive confidential, anonymous feedback
代碼片段
import csv
with open('data.csv') as input, open('out.csv','w') as output:
reader = csv.reader(input)
writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
for line in reader:
writer.writerow(line)
輸出
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members"," leaders"," and executives receive confidential"," anonymous feedback"
預期輸出
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members, leaders, and executives receive confidential, anonymous feedback"
uj5u.com熱心網友回復:
由于輸入資料不是普通的CSV檔案,使用csv模塊讀取輸入檔案可能會出現問題。為了解決這個問題,您可以直接讀取檔案的行,然后按如下方式決議它們:
import csv
with open('data.csv') as fin, open('out.csv','w') as fout:
writer = csv.writer(fout, delimiter=',', quoting=csv.QUOTE_ALL)
for line in fin:
writer.writerow(line.rstrip().split(',', 1))
uj5u.com熱心網友回復:
您可以使用DictReader,并DictWriter與restkey屬性:
with open('data.csv') as inp, open('out.csv', 'w') as out:
reader = csv.DictReader(inp, restkey='colN')
writer = csv.DictWriter(out, fieldnames=reader.fieldnames,
delimiter=',', quoting=csv.QUOTE_ALL)
writer.writeheader()
for line in reader:
line[reader.fieldnames[-1]] = ','.join(line.pop('colN', []))
writer.writerow(line)
內容out.csv:
"col1","col2"
"first row","This section of the badge focuses on Communications"
"second row","Feedback has partnered with team members leaders, and executives receive confidential, anonymous feedback"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401942.html
