Variable not updating on looping through csv files

Viewed 29

I have this code which scans the last date in 250 csv files to see if they are euqal to 2021.01.22. Ideally for each csv fiel that has the last row with date 2021.01.22 it would add 1 to the latest variable - for some reason it is not adding up - only shows latest=1 at the end.

import os
import pandas as pd

for filename in os.listdir("data"):
    df=pd.read_csv("data/{}".format(filename))
    df2=str(df.iloc[-1,0])
    latest=0
    if df2 == '2021.01.22':
        latest = latest+1

    print(filename)
    print(df2)

thank you!

2 Answers

You are resetting latest for each file in the list.

Try the following:

import os
import pandas as pd

latest=0

for filename in os.listdir("data"):
    df=pd.read_csv("data/{}".format(filename))
    df2=str(df.iloc[-1,0])
    if df2 == '2021.01.22':
        latest = latest+1

    print(filename)
    print(df2)

found the answer

latest=0

should be placed before the loop

Related