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 字符串转换为整型

Java RESTful API数据获取最佳实践
https://www.shuihudhg.cn/127391.html

Python 字符串动态创建变量:安全高效的实现方法
https://www.shuihudhg.cn/127390.html

PHP字符串查找:strpos、strstr、stripos、strripos详解及性能比较
https://www.shuihudhg.cn/127389.html

PHP数据库交互与数据显示:最佳实践与性能优化
https://www.shuihudhg.cn/127388.html

Python绘制精美猫图案:从基础图形到艺术创作
https://www.shuihudhg.cn/127387.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