Home > Mobile >  Get specific files from a folder and save them in a list
Get specific files from a folder and save them in a list

Time:09-26

I have different files in a folder and I would like to sort them and save the sorted ones in a list. My goal is to only save the files from the year 2021 with the ending '.txt'

import os
os.chdir(r"C:\Users\MyName\Desktop\Python-Files\Test_OS")
list = []

for file in os.listdir("."):
    date, fileName = file.split("-")
    name, fileFormat = fileName.split(".")
    i = 1
    print(date, name, fileFormat)
    if fileFormat == "txt" and date == f"0{i}.2021":
        list.append(file)
        i = i   1
        print(f"0{i}.2021")
        

My Folder looks like this:

'01.2020-Monatsabschluss.txt',
 '01.2021-Monatsabschluss.txt',
 '02.2021-Monatsabschluss.txt',
 '02.2021-Monatsabshluss.bmp',
 '03.2021-Monatsabschluss.txt',
 '04.2021-Monatsabschluss.txt',
 '05.2021-Monatsabschluss.txt',
 '06.2021-Monatsabschluss.txt'

If I execute my code the list only contains '01.2021-Monatsabschluss.txt'. What am I missing?

CodePudding user response:

The logic of the loop is off - you only increment i once after comparing against date. You'd need to keep increasing i in an inner loop to match 02, 03, etc.

However, it would be much simpler to use pathname globbing:

from glob import glob
filelist = glob("0?.2021-Monatsabschluss.txt")

which will give you:

['01.2021-Monatsabschluss.txt',
 '02.2021-Monatsabschluss.txt',
 '03.2021-Monatsabschluss.txt',
 '04.2021-Monatsabschluss.txt',
 '05.2021-Monatsabschluss.txt',
 '06.2021-Monatsabschluss.txt']

The ? will match any character, so if you want to restrict it to 1-9 (to specify a month), you could use the pattern "0[1-9].2021-Monatsabschluss.txt".

(also, it's best to not name a list list because list is the name of the built-in list type).

  • Related