Python Examples of Finding Path and Finding File Path

  • 2021-07-13 05:39:18
  • OfStack

Sys. path Specifies a list of strings used for module search paths

You can also add search paths to the Python environment through the append method of the sys module.

Sys. path. append ('/usr/bin/')

/usr/lib64/python2.6 python module default storage path

. pyc is a binary file, which is generated by compiling py file. The loading speed is improved, and it is an encrypted file, which is beneficial to confidentiality.

1: A simple and secure way to do this is to add a path profile to a directory in sys. path, most commonly in …/site-package/. The path configuration file has an extension of ". pth" and contains a separate path for every 1 line that is added to the list of sys. path (verified). The path in ". pth" can be either absolute or relative, or if it is relative, relative to the path that contains the ". pth" file.

2: Load path: Modify the site. py file in the Python standard library and edit sys. path. Unless the-S switch option is used, site. py is automatically introduced (executed) when the Python interpreter is loaded to load packages and modules from site-packages into sys. path of python. So, you can edit site. py and add the following two lines:

Import sys

sys.path.append('/test')

Unedit:

Undo the last operation (lowercase u)

Undo all modifications to the current line (capital U)

Restore the first undo (Ctrl + r, that is, redo)

1. Module comes with its own attributes


>>> import os 
>>> print os.__file__ 
/usr/lib64/python2.6/os.pyc 

2. Use inspect's Find File getfile method to get the address


>>> import os 
>>> import inspect 
>>> print inspect.getfile(os) 
/usr/lib64/python2.6/os.pyc 
>>> print inspect.getsourcefile(os) 
/usr/lib64/python2.6/os.py 

3. Method for finding modules using imp


>>> import os
>>> import imp
>>> print imp.find_module('os')
(<open file '/usr/lib64/python2.6/os.py', mode 'U' at 0x7fa598970540>, '/usr/lib64/python2.6/os.py', ('.py', 'U', 1))

Related articles: