Python 使用 IDLE 时的工作目录是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15821121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the working directory when using IDLE?
提问by Nathan2055
So, I'm learning Python and would like to create a simple script to download a file from the internet and then write it to a file. However, I am using IDLE and have no idea what the working directory is in IDLE or how to change it. How can I do file system stuff in IDLE if I don't know the working directory or how to change it?
所以,我正在学习 Python 并想创建一个简单的脚本来从互联网下载文件,然后将其写入文件。但是,我正在使用 IDLE 并且不知道 IDLE 中的工作目录是什么或如何更改它。如果我不知道工作目录或如何更改它,如何在 IDLE 中执行文件系统操作?
采纳答案by poke
You can easily check that yourself using os.getcwd:
您可以使用os.getcwd以下方法轻松检查自己:
>>> import os
>>> os.getcwd()
'C:\Program Files\Python33'
That's on my Windows machine, so it's probably the installation directory of Python itself.
那是在我的Windows机器上,所以它可能是Python本身的安装目录。
You can change that directory at runtime using os.chdir:
您可以在运行时使用os.chdir以下命令更改该目录:
>>> os.chdir('C:\Users\poke\Desktop\')
>>> os.getcwd()
'C:\Users\poke\Desktop'
>>> with open('someFile.txt', 'w+') as f:
f.write('This should be at C:\Users\poke\Desktop\someFile.txt now.')
This will—not surprisingly—create the file on my desktop.
这将(不足为奇)在我的桌面上创建文件。
回答by Ashwini Chaudhary
You can check that using os.getcwd():
您可以使用os.getcwd()以下方法检查:
In [1]: import os
In [2]: os.getcwd()
Out[2]: '/home/monty'
In [7]: os.chdir("codechef") #change current working directory
In [8]: os.getcwd()
Out[8]: '/home/monty/codechef'
os.chdir():
os.chdir():
In [4]: os.chdir?
Type: builtin_function_or_method
String Form:<built-in function chdir>
Docstring:
chdir(path)
os.getcwd():
os.getcwd():
Change the current working directory to the specified path.
In [5]: os.getcwd?
Type: builtin_function_or_method
String Form:<built-in function getcwd>
Docstring:
getcwd() -> path
Return a string representing the current working directory.
回答by user2246674
This will depend on OS and how IDLE is executed.
这将取决于操作系统以及 IDLE 的执行方式。
To change the (default) CWD in Windows, right click on the Short-cut Icon, go to "Properties" and change "Start In".
要更改 Windows 中的(默认)CWD,请右键单击快捷方式图标,转到“属性”并更改“开始于”。
回答by iCodeSometime
Here is an excerpt from usfca.edu
这是来自usfca.edu的摘录
If you want to be able to import your files easily in IDLE, you need to make sure the working directory for IDLE is set to the folder with all of your code. For example, my in-class code is located at the directory /Users/sjengle/Desktop/Code, so to change the working directory of IDLE I need to run the following two commands:
如果您希望能够在 IDLE 中轻松导入文件,您需要确保 IDLE 的工作目录设置为包含所有代码的文件夹。例如,我的课内代码位于目录/Users/sjengle/Desktop/Code,因此要更改IDLE的工作目录,我需要运行以下两个命令:
import os
os.chdir("/Users/sjengle/Desktop/Code")

