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