1

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)

AshBoy
  • 11
  • 1
  • Just add "and f.endswith(".txt")" in your list comprehension – Hussain Bohra May 18 '20 at 18:11
  • Does this answer your question? [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python) – xilpex May 18 '20 at 18:13

2 Answers2

1

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.

Prateek Dewan
  • 1,587
  • 3
  • 16
  • 29
1

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)]
Booboo
  • 38,656
  • 3
  • 37
  • 60