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

How to list all files in a directory

anonymity
Release: 2019-05-25 09:47:33
Original
4220 people have browsed it

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()
Copy after login

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template