简体   繁体   English

为什么 python 会在路径中添加额外的反斜杠?

[英]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.

相关问题 为什么在Python路径中需要4个反斜杠? - Why do I need 4 backslashes in a Python path? Python:为什么转义反斜杠会产生 2 个反斜杠? - Python: why does escaping a backslash produce 2 backslashes? Python:为什么我指定的 output 路径中的单反斜杠在输出时更改为双反斜杠并导致 FileNotFoundError? - Python: Why are the single-backslashes in my specified output path changed to double-backslashes when outputting and result in FileNotFoundError? 为什么我的 python 没有将当前工作目录添加到路径中? - Why does my python not add current working directory to the path? 为什么在python中使用os.path.exists()时反斜杠不起作用,而正斜杠却起作用? - Why don't backslashes work when using os.path.exists() in python but forward slashes do work? 为什么在 Python 中打印元组(列表、字典等)会使反斜杠加倍? - Why does printing a tuple (list, dict, etc.) in Python double the backslashes? 为什么Python字符串中的3个反斜杠等于4? - Why do 3 backslashes equal 4 in a Python string? 为什么此代码在使用“\n”时会额外添加一个空行? - Why does this code add an additional empty line when using "\n"? 为什么filechooser.selection添加一个附加航路点? - Why does filechooser.selection add an additional waypoint? Python:os.path.realpath() - 如何修复未转义的反斜杠? - Python: os.path.realpath() - how to fix unescaped backslashes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM