Find all directories and files of your laptop [clo

2019-09-25 07:51发布

问题:

How can we write code in Python​ to find all file system including files from root to each and every file of the current computer system.

回答1:

You can use the os.walk method. Here is an example:

# !/usr/bin/python

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

copied from http://www.tutorialspoint.com/python/os_walk.htm

See the full documentation: https://docs.python.org/2/library/os.html#os.walk



回答2:

Refer to the os module.
os.chdir(path) changes the working dir.
os.listdir() lists all the directories in your working dir.

If you wanna find all the directories of your current system, you need to iterate through your system using for example BFS search (https://en.wikipedia.org/wiki/Breadth-first_search).