List only files without folders in Python dirétorio

Asked

Viewed 762 times

1

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

I used:

import os
print os.listdir('/')

1 answer

2


According to the answers of that question and of that 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 folder mypath.


Cod2:

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

You can change *.txt for *.* to grab files with any type of extension. However, if your folder has a subfolder named pasta.pasta1, the command *.* return this subfolder as well...


Cod3:

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

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

  • Thanks, it worked with walk

  • 1

    @Will If the answer was helpful you can mark it as correct using the V on its left side.

  • Done brother. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.