Naj Naj - 6 months ago 14
Python Question

Return only certain filename without extension

So from a previous post which I asked I found the following code to work:

b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER')
f = []
for(dirpath, dirnames, filenames) in b:
f.extend(os.path.splitext(name)[0] for name in filenames)
break


However, now I would like this list to return only a certain type of file, such as only the files that are .JPEG or .GIF (still without extension).

I already tried to use fnmatch, but it didn't work..

After comments I changed the code to:

b = os.walk('C:\\Users\\USER\\Desktop\\FOLDER')
os.listdir('C:\\Users\\USER\\Desktop\\FOLDER')
f = []
for(dirpath, dirnames, filenames) in b:
f.extend(os.path.splitext(name)[0] for name in filenames if name.lower().endswith((".jpeg", ".gif")))

def save_to_file(text):
for name in f:
with open('C:\\Users\\USER\\Desktop\\FOLDER\\test.txt', mode='wt', encoding='utf-8') as myfile:
myfile.write('\n'.join(text))
myfile.write('\n')

save_to_file(f)

Answer

You can use str.endswith passing a tuple of extensions:

f.extend((os.path.splitext(name)[0] for name in filenames if name.lower().endswith((".jpeg", ".gif")))

I am not sure why you have a break in your for loop as that will mean you loop over one directory which you could be doing with os.listdir