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"
# ""
但我不知道它是否适用于文件的所有行。
添加回答
举报