Python relative and absolute paths --python combat (IX)

I. Background information

During the recent run python program, inadvertently I encountered this problem, there has been implementing a program ok colleagues, to how I have here a mistake, had reported the error looks like:
    FileNotFoundError: [Errno 2] No such file or directory: 'ui.qss'

It means that the program can not find this kind of document, by looking at the code, the program is the existence of this document. It seems that the code in question, after several positioning, I finally found the problem, is when I execute code, however, the code uses the relative path to a file outside really executed, so that the error will be reported. By this mistake, let me realize how bad their python basis, the difference does not matter, then fill it up.

Two basic methods:

1. os.getcwd()

Gets files in the current working directory path (absolute path) https://docs.python.org/2/library/os.html#os.getcwd

2. sys.path[0]

Gets files in the current working directory path (absolute path)
sys.argv [0] | path where the module is obtained (determined by whether the system is full name)
if the python command shows the call, such as python demo.py, will be an absolute path;
if direct execute scripts, such as ./demo.py, it will be a relative path.

3. __ file __

Get file path where (determined by whether the system is full name)
if display perform Python, will be an absolute path;
if by a relative path to execute the script ./pyws/path_demo.py directly, will be a relative path.

4. os.path.abspath(__ file __)

Path (absolute path) where access to documents

5. os.path.realpath(__ file __)

Path (absolute path) where access to documents

Three combat training:

path = os.getcwd()
path1 = os.path.join(path,"test.txt")

def dir_check():
    print("the pwd is:%s" % path)
    print("the full path is:%s" % path1)
    with open(path1) as file:
        css = file.readlines()
        print("%s" % css)

def print_dir():
    print("sys.path[0] = ", sys.path[0])
    print("__file__ = ", __file__)
    print("os.path.abspath(__file__) = ", os.path.abspath(__file__))
    print("os.path.realpath(__file__) = ", os.path.realpath(__file__))
if __name__ == '__main__':
    dir_check()
    print_dir()

 

As it relates to issues of confidentiality, the results of the program, I will not put out, and want to know their own implementation of it.

For most people, acquiring a skill is the fastest way to repeatedly practice.

Guess you like

Origin www.cnblogs.com/dylancao/p/11425821.html