如何从包含反斜杠字符的文件中执行 Python 代码
How to execute Python code from file with a backslash character in it
我正在尝试从一个包含路径 ("C:\Users\Documents\ect.") 的文件中 运行 Python 3.3 代码。当我尝试 运行 exec(commands) 时,它 returns 这个错误:
tuple: ("(unicode error) 'unicodeescape' codec can't decode bytes in position ...
我知道这是因为文件路径中的单个反斜杠字符,我知道如果它是反斜杠反斜杠它会起作用,但我不知道如何将反斜杠反斜杠换成反斜杠。我的代码看起来像这样:
filepath = HardDrive + "/Folder/" + UserName + "/file.txt"
file = open(filepath, 'r')
commands = file.read()
exec(commands)
文件中只有这样一条命令
os.remove("C:\Users\Documents\etc.")
文件中函数中的文件路径是自动返回的,我没法控制
简单
commands = commands.replace('\', '/')
放在 exec(commands)
之前会解决问题 if 这确实是关于反斜杠的存在(因为它会将每个反斜杠变成正斜杠)。
当然,如果文件中还有你想保留的反斜杠,那当然是个问题(这个简单的代码无法区分你想保留哪些,哪些要替换!)但是从你的问题描述来看在这种情况下,这不应该打扰你。
您可以在路径前使用 r,它将忽略所有转义字符。
os.remove(r"C:\Users\Documents\etc.")
喜欢this.So,
file = open(r"filepath", 'r')
除此之外,Windows 和 Linux 都接受 /
文件路径。所以你应该使用这个。不是\
,用这个/
。
在这里发表评论后;
file = open(r"{}".format(filepath), 'r')
假设你的变量是;
filepath = "c:\users\tom"
在它前面加上r and;
filepath = r"c:\users\tom"
然后使用;
file = open(r"{}".format(filepath), 'r')
您编辑问题后的最后编辑。
filepath = r"{}/Folder/{}/file.txt".format(HardDrive,UserName)
file = open(r"{}".format(filepath), 'r')
使用 str.replace
添加原始字符串 r
以转义文件中的文件名:
with open("{}/Folder/{}/file.txt".format(HardDrive, UserName)) as f:
(exec(f.read().replace("C:\",r"C:\")))
现在文件名将类似于 'C:\Users\Documents\etc.
'。
您可能还需要删除那个句点:
exec(f.read().rstrip(".").replace("C:\",r"C:\"))
我正在尝试从一个包含路径 ("C:\Users\Documents\ect.") 的文件中 运行 Python 3.3 代码。当我尝试 运行 exec(commands) 时,它 returns 这个错误:
tuple: ("(unicode error) 'unicodeescape' codec can't decode bytes in position ...
我知道这是因为文件路径中的单个反斜杠字符,我知道如果它是反斜杠反斜杠它会起作用,但我不知道如何将反斜杠反斜杠换成反斜杠。我的代码看起来像这样:
filepath = HardDrive + "/Folder/" + UserName + "/file.txt"
file = open(filepath, 'r')
commands = file.read()
exec(commands)
文件中只有这样一条命令
os.remove("C:\Users\Documents\etc.")
文件中函数中的文件路径是自动返回的,我没法控制
简单
commands = commands.replace('\', '/')
放在 exec(commands)
之前会解决问题 if 这确实是关于反斜杠的存在(因为它会将每个反斜杠变成正斜杠)。
当然,如果文件中还有你想保留的反斜杠,那当然是个问题(这个简单的代码无法区分你想保留哪些,哪些要替换!)但是从你的问题描述来看在这种情况下,这不应该打扰你。
您可以在路径前使用 r,它将忽略所有转义字符。
os.remove(r"C:\Users\Documents\etc.")
喜欢this.So,
file = open(r"filepath", 'r')
除此之外,Windows 和 Linux 都接受 /
文件路径。所以你应该使用这个。不是\
,用这个/
。
在这里发表评论后;
file = open(r"{}".format(filepath), 'r')
假设你的变量是;
filepath = "c:\users\tom"
在它前面加上r and;
filepath = r"c:\users\tom"
然后使用;
file = open(r"{}".format(filepath), 'r')
您编辑问题后的最后编辑。
filepath = r"{}/Folder/{}/file.txt".format(HardDrive,UserName)
file = open(r"{}".format(filepath), 'r')
使用 str.replace
添加原始字符串 r
以转义文件中的文件名:
with open("{}/Folder/{}/file.txt".format(HardDrive, UserName)) as f:
(exec(f.read().replace("C:\",r"C:\")))
现在文件名将类似于 'C:\Users\Documents\etc.
'。
您可能还需要删除那个句点:
exec(f.read().rstrip(".").replace("C:\",r"C:\"))