Python中的文件路径以字符串的形式出现错误 [英] File paths in Python in the form of string throw errors
问题描述
D:\ful_automate\dl
。但是Python会将某些字符识别为其他字符,并引发错误。在该示例中,错误是 IOError:[Errno 22]无效模式('wb')或filename:'D:\x0cul_automate\\\dl
。这对我来说很多,每次我需要将目录名称更改为可能没有问题的目录名称。 \
字符用于形成字符转义; \f
具有特殊含义。
使用 /
或者使用原始字符串 r'
。或者,您可以确保Python以反斜杠的形式读取反斜杠,并使用额外的 \
转义。
r'D:\ful_automate\dl'
'D:\\ful_automate\\\dl'
'D:/ ful_automate / dl'
演示以显示差异:
>>> 'D:\ful_automate\dl'
'D:\x0cul_automate\\\d1'
>>> r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
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.
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'
这篇关于Python中的文件路径以字符串的形式出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!