Python Path Summary

Source: Internet
Author: User

The delimiter for the file path under Windows is ' \ ' backslash, the file path is also a string, involving the ' \ ' in the Python string in the case of escaping, do a probe into this problem.

There are two ways to use ' \ ' in a Python string:

    • Use ' \ ' to escape, the notation is ' \ \ '. For example: "C:\\users\\xxx.txt"
    • String preceded by R force not escaped, writing R ' C:\users\xxx.txt '

The default in Python is the first way, using an escape string to represent the path, such as the path to the current directory returned by OS.GETCWD () can be found. When the second method is used, Python converts the string to the first result.

Operations involving paths are mostly stitching and splitting paths, but Python has encapsulated functions for these operations, Os.path.join (), Os.path.split (). We recommend that you use these functions to complete the segmentation and splicing operations, do not write their own, accidentally error.

The test code is as follows:

1>>>OS.GETCWD ()2 'C:\\users\\xdy\\desktop'3>>> F=open (OS.GETCWD () +r'\forher\out1.txt')4>>> F=open (OS.GETCWD () +'\forher\out1.txt')5 Traceback (most recent):6File"<pyshell#21>", Line 1,inch<module>7F=open (OS.GETCWD () +'\forher\out1.txt')8IOError: [Errno] Invalid argument:'C:\\users\\xdy\\desktop\x0corher\\out1.txt'9>>>Ten>>> Os.path.join (OS.GETCWD (),'Forher') One 'C:\\users\\xdy\\desktop\\forher' A>>>Os.path.sep - '\\'
View Code

Python Path Summary

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.