CSV文件包含以下数据,
“ 1111”“,” 2222“ 2222”,“ 3333,33,33”,“ 444”,“”
csv阅读器将这些数据读取为
['“” 1111“”','“ 2222” 2222“','” 3333','33','33“','” 444“','”“']]
当我尝试将此阅读器对象转换为列表并尝试对每个循环使用时,循环将“ 3333、33、33”视为三个不同的值。我的要求是将其作为单个字符串读取。
码:
reader = csv.reader(csv_file, delimiter=',', quotechar="'", escapechar = "'")
for row in reader:
colValues = list(row)
print(colValues)
for each in colValues:
print(each)
电流输出:
"1111""
"2222"2222"
"3333
33
33"
"444"
""
所需输出:
"1111""
"2222"2222"
"3333, 33, 33"
"444"
""
最佳答案
我认为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