Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

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. 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. Here is an excerpt of the csv file:

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:

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

question from:https://stackoverflow.com/questions/65905199/reading-last-non-empty-cell-in-row-of-csv-file-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try the below ('z.csv') is your data

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...