How does Python obtain the absolute path of the resource file?

Source: Internet
Author: User

There are two types of paths: relative path and absolute path. For a Unix-like system, the absolute path is the path starting. A relative path is a path that does not start with a slash.

In fact, there is only one path in the operating system, that is, the absolute path. Relative Path, onlyProgramHelp us change it to an absolute path.

The program running in the operating system uses environment variables to generate relative paths as absolute paths for us. The getcwd () function is used to obtain the current working path of the current process. That is, the starting point of the relative path.

In python, you can use the OS. chdir function to switch the current working path.

The current working path is the path where the program is executed. The directory in which the program is executed and the current path is in which directory.

We often need to execute some files under the source code directory in Python. For example, we may need to use eval to dynamically execute a Python source file. Or copy some configuration files to the path of the target system. At this time, we cannot know the absolute path of these files, because we cannot predict which directory the user will install our program.

We cannot depend on the current working path. Because the user may not execute our program in our source code directory.

Then, how can we get the absolute path of the files under the source code directory?

I did this:

Abspath = none

If _ name _ = '_ main __':

Abspath = OS. Path. abspath (SYS. argv [0])
Abspath = OS. Path. dirname (abspath) + "/"

Print abspath

By getting the absolute path of the first parameter, we know the absolute path of the program, we can use the global variable abspath to assemble the absolute path of any file in the source code directory!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.