Home >Backend Development >Python Tutorial >How to find current directory and file directory

How to find current directory and file directory

anonymity
anonymityOriginal
2019-05-25 16:19:334536browse

There are two functions under the os module:

os.walk()

os.listdir()

How to find current directory and file directory

# -*- coding: utf-8 -*-   
    import os   
    def file_name(file_dir):   
        for root, dirs, files in os.walk(file_dir):  
            print(root) #当前目录路径  
            print(dirs) #当前路径下所有子目录  
            print(files) #当前路径下所有非目录子文件

The output format is:

Current file directory path

Sub-file directory under the current path (if it exists, [] if it does not exist)

Under the current path Non-directory subfile (only the file name of the subfile)

Case:

# -*- coding: utf-8 -*-   
      
    import os  
      
    def file_name(file_dir):   
        L=[]   
        for root, dirs, files in os.walk(file_dir):  
            for file in files:  
                if os.path.splitext(file)[1] == '.jpeg':  
                    L.append(os.path.join(root, file))  
        return L  
#其中os.path.splitext()函数将路径拆分为文件名+扩展名

The above is the detailed content of How to find current directory and file 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