0

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, ...

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Iterate over the items in each row of the csv file.

If an item does not contain a value (''), then print the previous item (and go to the next row).


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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.