PYTHON如何获取当前工作目录
时间: 2023-08-22 20:03:28 浏览: 35
在Python中,可以使用os模块的getcwd()函数获取当前工作目录。代码如下:
```python
import os
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
```
输出结果为当前Python脚本所在的目录。
相关问题
python 获取当前文件目录
要获取当前文件的目录,您可以使用`os`模块中的`os.path`函数。以下是获取当前文件目录的示例代码:
```python
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
print(current_dir)
```
在上述代码中,`os.path.abspath(__file__)`返回当前文件的绝对路径,然后使用`os.path.dirname()`函数获取该路径的目录部分。最后,将结果打印出来。
请注意,这段代码应该在您需要获取当前文件目录的Python脚本中执行。它将打印出当前文件的目录路径。
python 获取当前目录
在 Python 中,你可以使用 `os` 模块来获取当前目录。具体可以使用 `os.getcwd()` 函数来获取当前工作目录的路径。下面是一个示例代码:
```python
import os
current_directory = os.getcwd()
print("当前目录:", current_directory)
```
输出将会是当前工作目录的绝对路径。
另外,如果你只需要获取当前脚本所在的目录,可以使用 `os.path.dirname()` 函数来获取脚本的目录路径。示例如下:
```python
import os
script_directory = os.path.dirname(os.path.abspath(__file__))
print("脚本所在目录:", script_directory)
```
这将输出脚本所在的目录的绝对路径。注意,使用 `__file__` 变量来获取当前脚本的文件路径。