+1 vote
in Python by (4.1k 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):



 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]

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 16, 2019 in Python by Sammy (47.8k points)
+1 vote
2 answers
+1 vote
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !