+1 vote
2 views
in Python by (3.2k points)
edited by

How can I list and add all files of a directory to a list in Python?

1 Answer

+2 votes
by (10.9k points)
edited by

You can use os.listdir() to list both the files and directories.

To list only files you may use os.path:

from os import listdir

from os.path import isfile, join

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

os.walk() may also be used in case you want two lists: one for files and another for directories.

from os import walk

f = []

for (dirpath, dirnames, filenames) in walk(mypath):

    f.extend(filenames)

Break

 To add one list with another you can use .extend() or,

>>> a = [10,11,12]

>>> b= [13, 14, 15]

>>> a = a + b

>>> a

[10,11, 12, 13, 14, 15]

...