我试图解决这个问题...我有csv文件,其中包含:
jmeno,prijmeni,roknarozeni
"adam","novak",1995
"petr","papousek",1992
"josef","petrklic",1985
我的努力:
import re
for line in open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv'):
line = line.replace('"','')
line = re.split('\W+', line)
print (line)
但输出是:
['jmeno', 'prijmeni', 'roknarozeni', '']
['adam', 'novak', '1995', '']
['petr', 'papousek', '1992', '']
['josef', 'petrklic', '1985', '']
而不是:
[['jmeno', 'prijmeni', 'roknarozeni', '']
['adam', 'novak', '1995', '']
['petr', 'papousek', '1992', '']
['josef', 'petrklic', '1985', '']]
答案 0 :(得分:0)
根本不需要re
。剥离"
并拆分,
,如果你想要一个列表列表,然后附加到一个列表:
out = []
with open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv') as f:
for line in f:
out.append([x.strip('"') for x in line.rstrip().split(",")])
[['jmeno', 'prijmeni', 'roknarozeni'], ['adam', 'novak', '1995'], ['petr', 'papousek', '1992'], ['josef', 'petrklic', '1985']]
或者替换和列表理解:
with open('C:\\Users\\Vlada\\Desktop\\SKOLA\\WVA\\csv.csv') as f:
print([line.replace('"',"").rstrip().split(",") for line in f])
[['jmeno', 'prijmeni', 'roknarozeni'], ['adam', 'novak', '1995'], ['petr', 'papousek', '1992'], ['josef', 'petrklic', '1985']]
我认为你不实际上想要列表中的空字符串。