Python generate text with format mydata_hh_mm

Viewed 30

I have a number of csv files with name following the rule: mydata_hh_mm such as mydata_09_00. hh is hour running from 06 to 09. mm is minute running from 00 to 59. I want to to generate the filename automatically so I can import them into a df? The problem is the 0 when there is only 1 digit in hh or mm, which make this code below not working.

for i in range(7,10):  
    for j in range(0,60):
        file='mydata_' + '0' + str(i) + '_' + str(j) + '.csv' 
        alldata = pd.concat([alldata, pd.read_csv(rf'....csv')])
        print(file)
1 Answers

Here is a method to try which uses f-strings and formatting.

for i in range(7,10):  
    for j in range(0,60):
        file = f'mydata_{i:02}_{j:02}.csv'
        print(file)

Essentially this works as: {value:width}. For example {2:05} will yield a string '2' padded to five characters: '00002'. Therefore your two character padding works as shown above.

Output:

mydata_07_00.csv
mydata_07_01.csv
...
mydata_09_58.csv
mydata_09_59.csv

Note: f-strings were introduced in Python 3.6.

Here is some additional reading on the subject.

Related