在Python 3中,获取路径通常使用`os`模块。以下是一些获取路径的方法:
1. 获取当前工作目录的路径:
```python
import os
current_path = os.getcwd()
print("当前路径:", current_path)
2. 获取当前文件的绝对路径:
```python
import os
current_file_path = os.path.abspath(__file__)
print("当前文件的绝对路径:", current_file_path)
3. 获取调用当前文件的父文件的路径:
```python
import inspect
def get_parent_file_path():
frame_stack = inspect.stack()
caller_frame = frame_stack
return os.path.abspath(caller_frame.f_code.co_filename)
print("调用当前文件的父文件的路径:", get_parent_file_path())
4. 获取命令行参数,即传递给脚本的路径列表:
```python
import sys
print("命令行参数列表:", sys.argv)
5. 列出当前路径下的文件夹和文件:
```python
import os
print("当前路径下的文件和文件夹:", os.listdir())
6. 递归获取目录和子目录下所有文件的列表:
```python
import os
for root, dirs, files in os.walk('.'):
for file in files:
print(os.path.join(root, file))
7. 使用`os.scandir`遍历目录,返回一个生成器:
```python
import os
for entry in os.scandir('.'):
print(entry.name)
8. 使用`glob`模块遍历路径,返回一个列表:
```python
import glob
for file in glob.glob('*.txt'):
print(file)
以上方法可以帮助你获取不同级别的路径信息。请根据你的需求选择合适的方法