Question

I am a little confused about the distinction between CWD and and import path in Python.

From what I understand:

C:\temp> python C:\...\PyTools\ex.py

The script file is in C:...\PP4E\Tools\ , but the script processes files located in C:\temp ? Or am I mistaking something?

Basically I have a script running from a certain directory, and I need it to process files in another directory.

C:\temp> python C:\...\PyTools\find.py *.py C:\...\Directory

Again From what I understand the script can access files in PyTools directory and processes files in \Directory. But the CWD remains \temp?

So is \temp added to the python path? Does CWD ever get added to the python path? I am a little confused, if some one can explain this to me I would be much obliged. Thanks.

Was it helpful?

Solution

Python's search path -- where it looks for modules named in import statements -- includes the contents of the PYTHONPATH environment variable, the value of sys.path, and the directory in which the running script was located. Your current working directory (cwd) is never part of Python's search path by default.

Your cwd when you start your Python script is the cwd of your script; this means that file operations, such as open(), will refer to files in your current directory absent any path qualifiers. For example, if you are in c:\temp, and you run a Python script, and you script does this...

fd = open('myfile.txt')

...then you will be opening c:\temp\myfile.txt.

If you want to open files in another directory, you can provide a full path to open:

fd = open('c:\\anotherdir\\myfile.txt')

Or you can call os.chdir() in your code:

os.chdir('c:\\anotherdir')
fd = open('myfile.txt')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top