Find All Files in a Directory With Extension .Txt in Python

Find all files in a directory with extension .txt in Python

You can use glob:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)

or simply os.listdir:

import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))

or if you want to traverse directory, use os.walk:

import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))

Python: How can I find all files with a particular extension?

try changing the inner loop to something like this

results += [each for each in os.listdir(folder) if each.endswith('.c')]

Find all files named *.txt in directory

mp3files = list(filter(lambda f: f.endswith('.txt') ,file))

Should work, since the file name do not match (==) to *.txt but rather end with that extension

How can find all files of the same extension within multiple subdirectories and move them to a seperate folder using python?

dswdsyd has the right answer here, although you could change the printout to actually move the files like so:

import os

path = 'C:\\location_to_root_folder\\'
newpath = 'C:\\NewPath\\'

files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.mpg' in file:
files.append(os.path.join(r, file))

for f in files:
os.rename(f, newpath + f.split('/')[-1])
print(f'{f.split('/')[-1]} moved to {newpath}')

Check if a directory contains a file with a given extension

You can use the else block of the for:

for fname in os.listdir('.'):
if fname.endswith('.true'):
# do stuff on the file
break
else:
# do stuff if a file .true doesn't exist.

The else attached to a for will be run whenever the break inside the loop is not executed. If you think a for loop as a way to search something, then break tells whether you have found that something. The else is run when you didn't found what you were searching for.

Alternatively:

if not any(fname.endswith('.true') for fname in os.listdir('.')):
# do stuff if a file .true doesn't exist

Moreover you could use the glob module instead of listdir:

import glob
# stuff
if not glob.glob('*.true')`:
# do stuff if no file ending in .true exists


Related Topics



Leave a reply



Submit