简体   繁体   中英

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:\Users\AZERTY\Desktop\1.1 pandas.zip\2021\'): 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?

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:\Users\AZERTY\Desktop\1.1 pandas.zip\2021\'):

You need to escape some parts of your string with a backslash:

'C: \Users\AZERTY\Desktop\\1.1 pandas.zip\\2021\\'

Assuming you are getting a string literal is undetermined error

Why does "\1" inside a triple-quoted string evaluate to a unicode 0x1 code point

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM