List only files without folders in directory in Python

1

I need to list files in a directory, but I need to list only the files, without showing any folder if you have that directory.

I used:

import os
print os.listdir('/')
    
asked by anonymous 24.04.2017 / 19:42

1 answer

2

According to Answers and < a href="https://stackoverflow.com/questions/14176166/list-only-files-in-a-directory"> of this other question , you can use commands like:

Cod1:

from os import listdir
from os.path import isfile, join

mypath = '/home/'

onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
print(onlyfiles)

Returns only the files in the mypath folder.

Cod2:

import glob
print glob.glob("/home/user/*.txt")

You can change *.txt to *.* to get files with any type of extension. However, if your folder has a subfolder with the name pasta.pasta1 , the *.* command will return that subfolder too ...

Cod3:

import os
filenames = next(os.walk(path))[2]

Returns only the third parameter of the walk method, which in this case is the filenames

    
24.04.2017 / 19:53