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 通过 TCP 发送数据