📜  Python - 列出目录中的文件

📅  最后修改于: 2022-05-13 01:55:40.862000             🧑  作者: Mango

Python - 列出目录中的文件

目录有时也称为文件夹,是计算机文件系统中用于存储和定位文件或多个文件夹的单元组织结构。 Python现在支持许多 API 来列出目录内容。例如,我们可以使用 Path.iterdir、os.scandir、os.walk、Path.rglob 或 os.listdir 函数。

使用目录: gfg

方法一:操作系统模块

  •   os.listdir()方法获取指定目录中所有文件和目录的列表。默认情况下,它是当前目录。

语法

os.listdir(path)

参数

目录路径

返回类型:返回指定路径中所有文件和目录的列表

示例 1:

Python
# import OS module
import os
 
# Get the list of all files and directories
path = "C://Users//Vanshi//Desktop//gfg"
dir_list = os.listdir(path)
 
print("Files and directories in '", path, "' :")
 
# prints all files
print(dir_list)


Python3
#import OS
import os
 
for x in os.listdir():
    if x.endswith(".txt"):
        # Prints only text file present in My Folder
        print(x)


Python3
# import OS module
import os
 
# This is my path
path="C://Users//Vanshi//Desktop//gfg"
 
# to store files in a list
list = []
 
# dirs=directories
for (root, dirs, file) in os.walk(path):
    for f in file:
        if '.txt' in f:
            print(f)


Python3
# import OS module
import os
 
# This is my path
path="C://Users//Vanshi//Desktop//gfg"
 
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir()
 
# List all files and directories in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj:
    if entry.is_dir() or entry.is_file():
        print(entry.name)


Python3
import glob
 
# This is my path
path="C:\\Users\\Vanshi\\Desktop\\gfg"
 
# Using '*' pattern
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
    print(files)
 
# Using '?' pattern
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
    print(files)
 
 
# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
    print(files)


Python3
import glob
 
# This is my path
path="C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"
 
 
 
# It returns an iterator which will
# be printed simultaneously.
print("\nUsing glob.iglob()")
 
# Prints all types of txt files present in a Path
for file in glob.iglob(path, recursive=True):
    print(file)


输出:

  

程序2:只获取txt文件。

蟒蛇3

#import OS
import os
 
for x in os.listdir():
    if x.endswith(".txt"):
        # Prints only text file present in My Folder
        print(x)

输出:

  •   OS.walk()在目录树中生成文件名。  

蟒蛇3

# import OS module
import os
 
# This is my path
path="C://Users//Vanshi//Desktop//gfg"
 
# to store files in a list
list = []
 
# dirs=directories
for (root, dirs, file) in os.walk(path):
    for f in file:
        if '.txt' in f:
            print(f)

输出:


  • os.scandir()支持Python 3.5 及更高版本。  

句法:

os.scandir(path = ‘.’)

返回类型:返回 os.DirEntry 对象的迭代器。

例子:

蟒蛇3

# import OS module
import os
 
# This is my path
path="C://Users//Vanshi//Desktop//gfg"
 
# Scan the directory and get
# an iterator of os.DirEntry objects
# corresponding to entries in it
# using os.scandir() method
obj = os.scandir()
 
# List all files and directories in the specified path
print("Files and Directories in '% s':" % path)
for entry in obj:
    if entry.is_dir() or entry.is_file():
        print(entry.name)

输出:

方法 2:使用 glob

glob模块用于检索与指定模式匹配的文件/路径名。

  • glob() 方法

使用 glob,我们可以使用通配符 (“*, ?, [ranges]) 使路径检索更加简单方便。

蟒蛇3

import glob
 
# This is my path
path="C:\\Users\\Vanshi\\Desktop\\gfg"
 
# Using '*' pattern
print('\nNamed with wildcard *:')
for files in glob.glob(path + '*'):
    print(files)
 
# Using '?' pattern
print('\nNamed with wildcard ?:')
for files in glob.glob(path + '?.txt'):
    print(files)
 
 
# Using [0-9] pattern
print('\nNamed with wildcard ranges:')
for files in glob.glob(path + '/*[0-9].*'):
    print(files)

输出:

  • 如果 recursive 参数设置为 True,则iglob()方法可用于递归打印文件名。

句法:

glob.glob(pathname, *, recursive=False)

例子:

蟒蛇3

import glob
 
# This is my path
path="C:\\Users\\Vanshi\\Desktop\\gfg**\\*.txt"
 
 
 
# It returns an iterator which will
# be printed simultaneously.
print("\nUsing glob.iglob()")
 
# Prints all types of txt files present in a Path
for file in glob.iglob(path, recursive=True):
    print(file)

输出: