Discuss python in detail in windows file path problem

  • 2020-08-22 22:16:06
  • OfStack

When using python to open a file via the open() function and passing the absolute path to open(), it is found that the content of the path parameter is not as expected:

Because the path separator for windows USES a backslash \, which is just an escape character, conflicts can occur


#  Error: The backslash appears to be interpreted as an escape character rather than a separator character 
path = '''F:\Python\test.txt'''    
path = '''F:\\Python\test.txt'''

""" The following 3 Either way, it works """
path = '''F:\Python\\test.txt'''
path = '''F:\\Python\\test.txt'''
path = '''F:\Python\\test.txt'''    
''' The end of the absolute path 1 Two backslashes are normal when double backslashes are used '''
''' And the reason is that in the end 1 A character with which the backslash can be next to it t Constitute an escape effect '''

Conclusion: When using an absolute path, pay attention to whether the backslash used in the absolute path and the character immediately following it form an escape effect. If an escape effect occurs, such as \t \n \r, etc., then you must use double backslashes to cancel the SLR backslash effect. open() prompts "Invalid arguments" if an error is caused by an escape character


Related articles: