如何从文件中执行带有反斜杠字符的Python代码

时间:2015-01-24 23:33:52

标签: python windows

我试图从包含路径(" C:\ Users \ Documents \ ect。")的文件中运行Python 3.3代码。当我尝试运行exec(命令)时,它返回此错误:

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.")

文件中函数中的文件路径会自动返回,我无法控制它。

3 个答案:

答案 0 :(得分:1)

一个简单的

commands = commands.replace('\\', '/')

exec(commands)之前放置将解决问题如果它确实是关于反斜杠的存在(因为它会将每一个转变成一个前锋斜线)。

当然,如果文件中还有你想要保留的反斜杠那么问题(这个简单的代码无法区分你想要保留哪些,哪些要替换!)但是你的问题描述在这种情况下不应该打扰你。

答案 1 :(得分:1)

您可以在路径前使用 r ,它会忽略所有转义字符。

os.remove(r"C:\Users\Documents\etc.")

喜欢这个。所以,

file = open(r"filepath", 'r')

除此之外,Windows和Linux都接受/这个文件路径。所以你应该使用它。不是\,请使用此/

在此发表评论后;

file = open(r"{}".format(filepath), 'r')

假设你的变量是;

filepath = "c:\users\tom"

r 放在它之前;

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')

答案 2 :(得分:1)

使用r添加原始字符串str.replace以转义文件中的文件名:

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:\\"))