简体   繁体   中英

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? 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.

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

Now from a dos box, you get the following output:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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