File paths in Python in the form of string throw errors

孤街醉人 提交于 2019-12-19 17:37:36

问题


I need to put a lot of filepaths in the form of strings in Python as part of my program. For example one of my directories is D:\ful_automate\dl. But Python recognizes some of the characters together as other characters and throws an error. In the example the error is IOError: [Errno 22] invalid mode ('wb') or filename: 'D:\x0cul_automate\\dl. It happens a lot for me and every time I need to change the directory name to one that may not be problematic.


回答1:


The \ character is used to form character escapes; \f has special meaning.

Use / or use raw string r'' instead. Alternatively, you could ensure that Python reads the backslash as a backslash by escaping it with an additional \.

r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
'D:/ful_automate/dl'

Demo to show the difference:

>>> 'D:\ful_automate\dl'
'D:\x0cul_automate\\dl'
>>> r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'



回答2:


Use raw string instead of string ie use r'filepath' It fixes the problem off blacklash "\"



来源:https://stackoverflow.com/questions/13955176/file-paths-in-python-in-the-form-of-string-throw-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!