我试图使用python获得csv文件每行中最后值的列表。这些行都有5个单元格,但是它们被不一致地填充。有些有一个、两个、三个或四个单元格,其余的是空的。以下是csv文件的摘录:
art and entertainment,books and literature,,,
art and entertainment,celebrity fan and gossip,,,
art and entertainment,comics and animation,anime and manga,,
art and entertainment,comics and animation,cartoons,,
art and entertainment,comics and animation,comics,,
art and entertainment,dance,ballet,,
art and entertainment,dance,ballroom dance,,
art and entertainment,dance,belly dance,,
art and entertainment,dance,modern dance,,
art and entertainment,dance,pole dancing,,
art and entertainment,dance,,,
art and entertainment,humor,,,
art and entertainment,movies,film festivals and awards,,
...
和期望的输出:
books and literature, celebrity fan and gossip, anime and manga, cartoons, comics, ballet, ...
试试下面('z.csv')是你的数据
with open('z.csv') as f:
lines = [l.strip() for l in f.readlines()]
for line in lines:
fields = line.split(',')
last_non_empty = [f for f in fields if f][-1]
print(last_non_empty)
遍历csv文件每行中的项。
如果某项不包含值(''
),则打印前一项(并转到下一行)。
with open('file.csv', 'r') as csvfile:
data = csv.reader(csvfile)
for row in data:
prevItem = ''
for item in row:
if not item:
print(prevItem)
break
prevItem = item