Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
5 views
in Python by (4k 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]

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...