繁体   English   中英

使用 Python 读取 CSV 文件行中的最后一个非空单元格

[英]Reading last non-empty cell in row of CSV file with Python

我正在尝试使用 python 获取 csv 文件的每一行中最后一个值的列表。 这些行都有五个单元格,但它们的填充不一致。 有些有一个、两个、三个或四个填充了 rest 空的单元格。 这是 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,,
...

和所需的 output:

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 文件的每一行中的项目。

如果项目不包含值 ( '' ),则打印前一个项目(并将 go 打印到下一行)。


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM