2 回答

TA貢獻1873條經驗 獲得超9個贊
我認為該csv模塊無法處理這種不規則格式。
您可以根據","哪個將獲得正確的列進行拆分。您還需要去除第一個和最后一個引號。
>>> row = '"1111"","2222"2222","3333, 33, 33","444",""'
>>> row = row[1:-1]
>>> print(row)
1111"","2222"2222","3333, 33, 33","444","
>>> row.split('","')
['1111"', '2222"2222', '3333, 33, 33', '444', '']
共:
with open(csv_file) as lines:
for line in lines:
line = line.rstrip() # need to get rid of newline
for element in line[1:-1].split('","'):
print(element)
輸出:
1111"
2222"2222
3333, 33, 33
444

TA貢獻1860條經驗 獲得超9個贊
csv給定輸入字符串,沒有庫的解決方法:
input = '"1111"","2222"2222","3333, 33, 33","444",""'
這是返回所需的輸出:
res = input.split(",\"")
for i, e in enumerate(res):
if len(e) > 1 and e[0] != '"' or len(e) == 1:
res[i] = '"' + e
for e in res:
print (e)
# "1111""
# "2222"2222"
# "3333, 33, 33"
# "444"
# ""
但我不知道它是否適用于文件的所有行。