简体   繁体   English

为什么我们需要更改当前目录?

[英]Why we need to change our current directory?

If we can directly access and manipulate files in other directories (for example, using the Python code below), when would we need to change our current working directory? 如果我们可以直接访问和操作其他目录中的文件(例如,使用下面的Python代码),那么何时需要更改当前工作目录? What is the advantage of changing the current directory? 更改当前目录有什么好处?

import os
print(os.getcwd())
f=open(os.path.join(os.getcwd(),"test_folder")+"\\testfile","w")
f.close()
print(os.getcwd())
os.makedirs("test_folder_2")
print(os.getcwd())

Output: 输出:

c:\Users\me
c:\Users\me
c:\Users\me

In the example you're not changing the working directory. 在示例中,您没有更改工作目录。 You're just getting (printing) it. 您只是得到(打印)它。 You do not need to change the working directory. 您不需要更改工作目录。 But it's just like you are navigating your files from explorer, to keep your files organised. 但这就像您正在从资源管理器中浏览文件,以保持文件井井有条。 Sometimes it's done for the file permissions. 有时是为了获得文件权限。

The current working directory is the base directory for relative paths. 当前工作目录是相对路径的基本目录。 It is the place where you start looking for files and folders, if you don't supply an absolute path. 如果您没有提供绝对路径,那么它就是您开始查找文件和文件夹的地方。 Execute the following script from 2 different directories and examine the difference. 从2个不同的目录执行以下脚本,并检查差异。

# a.py
import os
print "\tcwd:", os.getcwd()
print "\tpth:", os.path.abspath("a")

Now from a dos box, you get the following output: 现在,从dos框中,您将获得以下输出:

C:\Users\user> python a.py
        cwd: C:\Users\user
        pth: C:\Users\user\a
C:\Users\user> cd ..
C:\Users> python user\a.py
        cwd: C:\Users
        pth: C:\Users\a

From a different working directory, you target different files with relative paths. 在不同的工作目录中,可以使用相对路径来定位不同的文件。 It is generally a good idea to use relative paths, because otherwise a script may only work for a single user, or the installation directory of a program must be the same on all computers, which is usually not the case. 通常,使用相对路径是一个好主意,因为否则脚本可能仅适用于单个用户,或者程序的安装目录在所有计算机上必须相同,通常不是这种情况。 You must change the working directory to target files and directories correctly with relative paths. 您必须将工作目录正确更改为带有相对路径的目标文件和目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM