How I list oly txt files of a directory?... how i filter to txt files
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir("D:\hacking\python") if isfile(
join("D:\hacking\python", f))]
print(onlyfiles)
How I list oly txt files of a directory?... how i filter to txt files
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir("D:\hacking\python") if isfile(
join("D:\hacking\python", f))]
print(onlyfiles)
You can add an and
condition in the list comprehension to check for the file extension as follows:
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir("D:\hacking\python") if isfile(
join("D:\hacking\python", f)) and f.endswith(".txt")]
print(onlyfiles)
The .endswith()
function is pretty self-explanatory; it checks if a string ends with a given substring.
You can use function function glob
from module glob
, which supports wildcards and returns full path names. If you are certain that all paths ending in .txt
are always regular files (or if you don't care and you just want all paths ending in .txt
regardless of what type of path it is), then the code is simply:
import glob
onlyfiles = glob.glob(r"D:\hacking\python\*.txt")
Otherwise:
import glob
from os.path import isfile
onlyfiles = [x for x in glob.iglob(r"D:\hacking\python\*.txt") if isfile(x)]
Note: iglob
returns an iterator rather than a list and is therefore more efficient to use in this case.
And if you do not want full path names:
import glob
from os.path import isfile, split
onlyfiles = [split(x)[-1] for x in glob.iglob(r"D:\hacking\python\*.txt") if isfile(x)]