Python absolute path and relative path

Source: Internet
Author: User

Turn from 49453953

The following paths are described for Windows, and other platforms are not very well known for the time being.

When you open a file in a py file that you write, you often see the following path:

Open ('aaa.txt')  open ('/data/bbb.txt')  Open ('d:\\user\\ccc.txt')  

Of these three expressions, the first two are relative and the third is the absolute path. The absolute path is better understood, is the most complete path, relative path relative is incomplete path, this relative refers to the current folder path, in fact, you write this PY file folder path! This means that the relative path you write must be the file a in the current folder A or folder B in the A to open.

Assume that the current Py folder is located in: D:\user\public

Then three lines of code open files that belong to the path are:

D:\user\public\aaa.txt

D:\user\public\data\bbb.txt

D:\user\private\ccc.txt

It's good to understand that when you open a file in a py file, you just use a relative path, and the absolute path is used to use a different folder.

Note: We often use '/' to denote a relative path, ' \ ' to represent an absolute path, where \ \ is the meaning of escaping . In addition, the Web site URL and Linux, Unix system generally used '/'.

Of course we can also get the absolute path of the current folder, as follows :

import os  path1=os.path.abspath ('. ' )   #表示当前所处的文件夹的绝对路径  path2=os.path.abspath ('.. ')  #表示当前所处的文件夹上一级文件夹的绝对路径  

So we often set a path1 global variable to represent the current absolute path, plus a relative path to open the file that needs to be opened, so that it does not conflict on different platforms, because there are differences in the representation of the different platforms on the relative path.

Python absolute path and relative path

Related Article

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.