如何在 Python shell 中知道/更改当前目录?[重复]
- 2025-04-15 09:19:00
- admin 原创
- 28
问题描述:
我在 Windows 7 上使用 Python 3.2。当我打开 Python shell 时,如何知道当前目录是什么?如何将其切换到另一个目录(我的模块所在的目录)?
解决方案 1:
您可以使用该os
模块。
>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'
但如果是为了寻找其他模块:你可以设置一个名为的环境变量PYTHONPATH
,在 Linux 下就像
export PYTHONPATH=/path/to/my/library:$PYTHONPATH
然后,解释器也会在此处搜索import
ed 模块。我猜在 Windows 下名称应该相同,但不知道如何更改。
编辑
在 Windows 下:
set PYTHONPATH=%PYTHONPATH%;C:My_python_lib
(摘自http://docs.python.org/using/windows.html)
编辑2
...甚至更好:使用virtualenv
和virtualenv_wrapper
,这将允许您创建一个开发环境,您可以在其中根据需要添加模块路径(add2virtualenv
),而不会污染您的安装或“正常”工作环境。
http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html
解决方案 2:
你想要
import os
os.getcwd()
os.chdir('..')
解决方案 3:
>>> import os
>>> os.system('cd c:mydir')
实际上,os.system()
可以执行 Windows 命令提示符可以执行的任何命令,而不仅仅是更改目录。
解决方案 4:
在 Python 中更改当前工作目录最简单的方法是使用 os 包。下面是一个 Windows 电脑的示例:
# Import the os package
import os
# Confirm the current working directory
os.getcwd()
# Use '\\' while changing the directory
os.chdir("C:\/user\\foldername")
解决方案 5:
更改当前目录不是处理 Python 中查找模块的方法。
相反,请参阅模块搜索路径的文档,了解 Python 如何找到要导入的模块。
以下是标准模块部分的相关内容:
变量 sys.path 是一个字符串列表,用于确定解释器模块的搜索路径。它会被初始化为从环境变量 PYTHONPATH 获取的默认路径,如果未设置 PYTHONPATH,则使用内置默认值。您可以使用标准列表操作来修改它:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
回答有关获取和设置当前目录的原始问题:
>>> help(os.getcwd)
getcwd(...)
getcwd() -> path
Return a string representing the current working directory.
>>> help(os.chdir)
chdir(...)
chdir(path)
Change the current working directory to the specified path.
解决方案 6:
如果你import os
可以使用os.getcwd
来获取当前工作目录,并且可以使用os.chdir
来更改目录
解决方案 7:
你可以尝试这个:
import os
current_dir = os.path.dirname(os.path.abspath(__file__)) # Can also use os.getcwd()
print(current_dir) # prints(say)- D:abcdefghijklmno"
new_dir = os.chdir('..\\..\\..\\')
print(new_dir) # prints "D:abcdefghi"
扫码咨询,免费领取项目管理大礼包!