[英]Why does python add additional backslashes to the path?
I have a text file with a path that goes like this:我有一个文本文件,其路径如下:
r"\\user\data\t83\rf\Desktop\QA"
When I try to read this file a print a line it returns the following string, I'm unable to open the file from this location:当我尝试读取此文件并打印一行时,它返回以下字符串,我无法从该位置打开文件:
'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
Seems you've got Python code in your text file, so either sanitize your file, so it only includes the actual path (not a Python string representation) or you can try to fiddle with string replace until you're satisfied, or just evaluate the Python string.似乎你的文本文件中有 Python 代码,所以要么清理你的文件,所以它只包含实际路径(不是 Python 字符串表示),或者你可以尝试摆弄字符串替换,直到你满意为止,或者只是评估Python 字符串。
Note that using eval()
opens Padora's box (it as unsafe as it gets), it's safer to use ast.literal_eval()
instead.请注意,使用
eval()
会打开 Padora 的盒子(它是不安全的),使用ast.literal_eval()
会更安全。
import ast
file_content = 'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
print(eval(file_content)) # do not use this, it's only shown for the sake of completeness
print(ast.literal_eval(file_content))
Output: Output:
\\user\data\t83\rf\Desktop\QA
\\user\data\t83\rf\Desktop\QA
Personally, I'd prefer to sanitize the file, so it only contains \\user\data\t83\rf\Desktop\QA
就个人而言,我更喜欢清理文件,所以它只包含
\\user\data\t83\rf\Desktop\QA
\
will wait for another character to form one like \n
(new line) or \t
(tab) therefore a single backslash will merge with the next character. \
将等待另一个字符形成一个,如\n
(新行)或\t
(制表符),因此单个反斜杠将与下一个字符合并。 To solve this if the next character is \\
it will represent the single backslash.如果下一个字符是
\\
来解决这个问题,它将代表单个反斜杠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.