Skip to content
Advertisement

Loop through files in folder, read and group files

I am trying to read a csv file, resample it and save it with a different name

So far I got this:

import fnmatch
import os

for file in os.listdir('C:UsersAZERTYDesktop1.1 pandas.zip2021'):
    if fnmatch.fnmatch(file, '*.csv'):
        mydata = pd.read_csv(file)
        mydata.columns = ["Date-Time", "Frequency"]
        mydata['Date-Time'] = pd.to_datetime(mydata['Date-Time'])
        mydata = mydata.set_index('Date-Time')
        mydata.index = pd.to_datetime(mydata.index)
        df = mydata.resample('1S').mean()
        df = df.fillna('nearest')
        df.to_csv(file +'fixed' +'.csv')

But I get an error due to syntax being wrong, any ideas?

Advertisement

Answer

One error I could see is that you use backslashes (“”) in your path. The backslash serves as escape character in python strings which means that the backslash together with the following symbol could have a special meaning. You should double all backslashes in paths like so:

for file in os.listdir('C:\Users\AZERTY\Desktop\1.1 pandas.zip\2021\'):

Or alternatively you can use pythons “raw” string by putting an “r” in front of it like this:

for file in os.listdir(r'C:UsersAZERTYDesktop1.1 pandas.zip2021'):
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement