Find files on disk

Python looks for files using path information from three sources:

  • environment variables – environment variables (such as PYTHONPATH) that contain a list of directories to search for files.
  • current directory – Python can access files in contained in the current directory.
  • default directories – Python can find files contained in the set of default directories included in the path information.

To list your path information, the following code can be used:

import sys
for p in sys.path:
    print(p)

We’ve used the sys module to get access to the system and environment-specific variables and parameters. Here is the result:

>>>
C:/Python34/Scripts
C:\Python34\Scripts
C:\Python34\Lib\idlelib
C:\Windows\SYSTEM32\python34.zip
C:\Python34\DLLs
C:\Python34\lib
C:\Python34
C:\Python34\lib\site-packages
>>>
Your output will probably be different from the one above, depending on your Python version, OS version, etc.

 

To add a path to the sys.path attribute, use the following code:

import sys

sys.path.append("E:\\backup")

for p in sys.path:
    print(p)

The output of the code above:

>>>
C:/Python34/Scripts
C:\Python34\Scripts
C:\Python34\Lib\idlelib
C:\Windows\SYSTEM32\python34.zip
C:\Python34\DLLs
C:\Python34\lib
C:\Python34
C:\Python34\lib\site-packages
E:\backup
>>>

To change the current Python directory, the following code can be used:

import os
os.chdir("C:\Python34\Scripts")
Geek University 2022