简体   繁体   English

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

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

I am trying to get a list of the last value in each row of a csv file using python.我正在尝试使用 python 获取 csv 文件的每一行中最后一个值的列表。 The rows all have five cells, but they are inconsistently filled up.这些行都有五个单元格,但它们的填充不一致。 Some have one, two, three, or four cells filled with the rest empty.有些有一个、两个、三个或四个填充了 rest 空的单元格。 Here is an excerpt of the csv file:这是 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,,
...

and the desired output:和所需的 output:

books and literature, celebrity fan and gossip, anime and manga, cartoons, comics, ballet, ...

Try the below ('z.csv') is your data试试下面的('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)

Iterate over the items in each row of the csv file.遍历 csv 文件的每一行中的项目。

If an item does not contain a value ( '' ), then print the previous item (and go to the next row).如果项目不包含值 ( '' ),则打印前一个项目(并将 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