Python os.listdir()方法 --获取目录和文件名称

os.listdir() 方法可以获取指定文件夹下的文件夹名和文件名

开发环境

windows10
python3.8.6
VSCode

os 模块是个标准库,不需额外安装

格式及参数

os.listdir(path)

path 文件夹路径,绝对路径和相对路径都可

返回值的类型是 列表

实例

以获取 hexo 根目录下的文件夹名和文件名为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import os

# 本地文件夹路径,这里使用绝对路径
path = r"D:\开发\hexo"
# 获取名称
file = os.listdir(path)
print(file)
# ['.deploy_git', '.git', '.gitignore', 'db.json', 'node_modules', 'package-lock.json', 'package.json', 'public', 'scaffolds', 'source', 'themes', '_config.yml']

# 将提取出的数据写入csv文件
with open('./hexo.csv', 'w', encoding='utf-8') as f:
for name in file:
# 每个名称占据一行
f.write(name + '\n')

windows 系统使用绝对路径时,斜杠 \ 需做处理

1
2
3
4
5
# 使用 \\ 代替 \
'C:\\a\\b\\c\\11.txt'

# 引号前加上字母 r
r'C:\a\b\c\11.txt'