比如说什么目录路径
时间: 2025-09-15 13:06:21 AIGC 浏览: 2
在 Python 程序中列举磁盘目录下所有 .txt 文件时,目录路径可以是相对路径或绝对路径。
### 相对路径
相对路径是相对于当前工作目录的路径。当前工作目录是指 Python 脚本运行时所在的目录。例如,如果 Python 脚本和要搜索的目录在同一层级,可使用相对路径来指定目录。
```python
import os
# 假设要搜索当前目录下的 sub_dir 目录中的 .txt 文件
directory = 'sub_dir'
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
for txt_file in txt_files:
print(txt_file)
```
### 绝对路径
绝对路径是从文件系统的根目录开始的完整路径。在 Windows 系统中,绝对路径通常以盘符(如 C:、D:)开头;在 Linux 或 macOS 系统中,绝对路径以斜杠(/)开头。
```python
import os
# Windows 系统示例
directory = 'C:\\Users\\Username\\Documents\\TextFiles'
# Linux 或 macOS 系统示例
# directory = '/home/username/Documents/TextFiles'
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
for txt_file in txt_files:
print(txt_file)
```
### 路径处理
在处理路径时,建议使用 `os.path.join()` 函数来构建路径,这样可以确保在不同操作系统上路径分隔符的正确性。
```python
import os
# 假设要搜索用户主目录下的 Documents 目录中的 .txt 文件
user_home = os.path.expanduser('~')
directory = os.path.join(user_home, 'Documents')
txt_files = [f for f in os.listdir(directory) if f.endswith('.txt')]
for txt_file in txt_files:
print(txt_file)
```
阅读全文
相关推荐




















