Home  >  Article  >  Backend Development  >  How to list all files in a directory

How to list all files in a directory

anonymity
anonymityOriginal
2019-05-25 09:13:404151browse

First of all, this type of requirement requires the operation of files and file paths. The libraries that need to be used are the os library and the glob library.

How to list all files in a directory

There are many ways to implement the requirements:

NO.1 Use os.listdir

#!usr/bin/env python
#-*-coding:utf-8 -*-
 
import os
 
def main():
    '''
    输出该路径下所有的文件夹及文件名字
    '''
    dir_aim = raw_input("请输入目标路径:")
    for filename in os.listdir(dir_aim):
        print filename
if __name__=='__main__':
    main()

NO.2 Use the glob module

#!usr/bin/env python
#-*-coding:utf-8 -*-
 
import glob
 
def main():
    '''
    输出该路径下所有的文件夹及文件的路径
    '''
    dir_aim = raw_input("请输入目标路径:")
    for filename in glob.glob(dir_aim):
        print filename
if __name__=='__main__':
    main()

You can filter file types by adding restrictions

For example, filter exe files:

\*.exe

NO.3 Use os.walk to traverse recursively

#!usr/bin/env python
#-*- utf-8 -*-
 
import os
 
def main():
    '''
    读取制定路径下的所有文件
    '''
    dir_aim = raw_input("请输入所要查看的文件目录:")
    for root, dirs, files in os.walk(dir_aim):
        print 'root:', root
        if files:
            print 'File:'
            for file in files:
                print file,
            print ''
        if dirs:
            for dir in dirs:
                print dir
 
if __name__=='__main__':
    main()

When Chinese characters exist in the file path, garbled characters will appear in print

The above is the detailed content of How to list all files in a directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn