-1

I tried to print all the files' name of a directory:

import os

dir = '/etc'


def fr(dir):
    filelist = os.listdir(dir)
    for i in filelist:
        fullfile = os.path.join(dir, i)
        if not os.path.isdir(fullfile):

            print(fullfile)
    else:
        fr(fullfile)

fr(dir)

But the result is like bellow:

.....
/etc/man.conf
/etc/manpaths
/etc/master.passwd
/etc/master.passwd~orig
/etc/my.cnf
/etc/my.cnf.bak
/etc/nanorc
/etc/networks
/etc/networks~orig
/etc/newsyslog.conf
/etc/nfs.conf
/etc/nfs.conf~orig
/etc/notify.conf
.....

You know, under the /etc/ssh/, there are many files, but it did not print, only print the first level files. the second level files and more deep files did not print.

Someone can help me to print all the files name?

user7693832
  • 6,119
  • 19
  • 63
  • 114
  • try `os.walk()` – M. Leung Nov 03 '17 at 09:31
  • `[os.path.join(dp, f) for dp, dn, filenames in os.walk('/etc') for f in filenames]` from [here](https://stackoverflow.com/questions/18394147/recursive-sub-folder-search-and-return-files-in-a-list-python) – p-robot Nov 03 '17 at 09:33
  • 1
    You need to recurse into directories if you want to print their contents. But there's no need to do this manually. You _could_ use `os.walk`. Or if you have a recent Python 3, look at the wonderful `pathlib` module. – PM 2Ring Nov 03 '17 at 09:34
  • I think glob is the easiest: `from glob import glob` `pathnames = glob('./**/*')` – Hielke Walinga Nov 03 '17 at 09:37
  • @HielkeWalinga Thanks for the tip. How to implement your method in specific folder (not current folder)? – Cloud Cho Jul 07 '23 at 06:25
  • 1
    @CloudCho Just use `glob('path/to/specific/folder/**/*', recursive=True)` to only traverse a path to the specific folder. This path can be relative or absolute (if you start the path with a `/`. – Hielke Walinga Jul 10 '23 at 09:09

1 Answers1

1

you can do it with import os it could be like this: import os

for dirname, dirnames, filenames in os.walk('C:/'): #provide which folder you need to list
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

The result would be like this:

======== RESTART: C:\dev\sandbox\test.py ========
C:/$Recycle.Bin
C:/boot
C:/dev
C:/Documents and Settings
C:/_SMSTaskSequence
C:/appConfig.json
C:/BOOTSECT.BAK
C:/dev.7z
C:/for
......
C:/test.txt

and etc.:

Refference: Directory listing in Python

simkusr
  • 770
  • 2
  • 11
  • 20