我正在尝试从带有路径的文件(“C:\Users\Documents\ect”)运行Python3.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.")文件中函数中的文件路径将自动返回,我无法控制它。
发布于 2015-01-24 23:51:43
使用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:\\"))发布于 2015-01-24 23:38:19
一个简单的
commands = commands.replace('\\', '/')就在exec(commands)之前,会修复问题,如果确实是因为反斜杠的存在(因为它会把每一个反斜杠都变成正斜杠)。
当然,如果文件中也有您想要保留的反斜杠(这段简单的代码无法区分您想要保留的是哪些,哪些要替换!)但是从你的问题描述来看,在这种情况下,这不应该让你感到困扰。
发布于 2015-01-24 23:39:22
您可以在路径之前使用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放在前面;
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')https://stackoverflow.com/questions/28131503
复制相似问题