Python 中获取文件目录52
在 Python 中,你可以使用以下几种方法来获取文件目录。
()
最简单的方法是使用 () 函数。它返回指定目录中所有文件的名称列表,不包括子目录。```
import os
# 获取当前目录中的文件列表
files = (".")
# 遍历文件列表并打印文件名
for file in files:
print(file)
```
()
你可以使用 () 函数根据模式匹配来获取文件列表。模式可以包含通配符,例如 * 和 ?。```
import glob
# 获取当前目录中所有以 .txt 结尾的文件
files = ("*.txt")
# 遍历文件列表并打印文件名
for file in files:
print(file)
```
()
如果你需要跨平台兼容性,可以使用 () 函数来调用系统命令 ls 或 dir,并捕获其输出。```
import subprocess
# 获取 Linux/macOS 中当前目录中的文件列表
command = "ls"
process = (command, shell=True, stdout=)
output = ()[0].decode("utf-8")
files = ()
# 遍历文件列表并打印文件名
for file in files:
print(file)
```
()
在 Python 3.6 及更高版本中,你可以使用 () 方法来获取目录中文件的生成器对象。```
from pathlib import Path
# 获取当前目录中的文件列表
path = Path(".")
files = list(())
# 遍历文件列表并打印文件名
for file in files:
print(file)
```
其他的方法
还有其他方法可以获取文件目录,例如使用 shutil.disk_usage()、walkdir() 或第三方库,例如 scandir。
获取子目录
要获取子目录,你可以使用 () 函数或 () 方法。```
import os
# 获取当前目录中的所有文件和子目录
for root, dirs, files in ("."):
print(root, dirs, files)
```
```
from pathlib import Path
# 获取当前目录中的所有子目录
path = Path(".")
subdirs = [d for d in ("*") if d.is_dir()]
# 遍历子目录列表并打印子目录名
for subdir in subdirs:
print(subdir)
```
2024-10-30
上一篇:Python 字符串转换为整型
Python代码数星星:从入门到实践的夜空模拟之旅
https://www.shuihudhg.cn/134238.html
Python开发者:驾驭大数据浪潮,解锁职业新篇章
https://www.shuihudhg.cn/134237.html
Python文件操作与异常处理:构建健壮可靠应用的基石
https://www.shuihudhg.cn/134236.html
C++ setw函数深度解析:掌控输出宽度与对齐的艺术
https://www.shuihudhg.cn/134235.html
Java高效字符匹配:从基础到正则表达式与高级应用
https://www.shuihudhg.cn/134234.html
热门文章
Python 格式化字符串
https://www.shuihudhg.cn/1272.html
Python 函数库:强大的工具箱,提升编程效率
https://www.shuihudhg.cn/3366.html
Python向CSV文件写入数据
https://www.shuihudhg.cn/372.html
Python 静态代码分析:提升代码质量的利器
https://www.shuihudhg.cn/4753.html
Python 文件名命名规范:最佳实践
https://www.shuihudhg.cn/5836.html