复制文件会引发SyntaxError无法解码字节

时间:2017-02-10 14:38:57

标签: python python-3.x

我正在尝试编写一个简短的程序,只要我运行它就会备份文件夹。目前它是这样的:

import time
import shutil
import os

date = time.strftime("%d-%m-%Y")
print(date)

shutil.copy2("C:\Users\joaop\Desktop\VanillaServer\world","C:\Users\joaop\Desktop\VanillaServer\Backups")

for filename in os.listdir("C:\Users\joaop\Desktop\VanillaServer\Backups"):
    if filename == world:
        os.rename(filename, "Backup " + date)

但是我收到错误:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 

我无法弄清楚为什么(根据文档,我认为我的代码写得正确)

我该如何解决这个问题/以更好的方式做到这一点?

2 个答案:

答案 0 :(得分:2)

在Python中,\u...表示Unicode序列,因此您的\Users目录被解释为Unicode字符 - 不是很成功。

>>> "\u0061"
'a'
>>> "\users"
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \uXXXX escape

要解决此问题,您应该将\转义为\\,或使用r"..."使其成为原始字符串。

>>> "C:\\Users\\joaop\\Desktop\\VanillaServer\\world"
'C:\\Users\\joaop\\Desktop\\VanillaServer\\world'
>>> r"C:\Users\joaop\Desktop\VanillaServer\world"
'C:\\Users\\joaop\\Desktop\\VanillaServer\\world'
但是,不要做两件事,否则他们将被逃脱两次:

>>> r"C:\\Users\\joaop\\Desktop\\VanillaServer\\world"
'C:\\\\Users\\\\joaop\\\\Desktop\\\\VanillaServer\\\\world'

您只需在源中直接输入路径时将其转义;如果您从文件,用户输入或某些库函数中读取这些路径,它们将自动转义。

答案 1 :(得分:1)

反斜杠用于转义字符,因此当解释器在文件路径字符串中看到\时,它会尝试将它们用作转义符(对于新行和{{\n类似1}}用于标签)。

有两种方法可以解决此问题,使用原始字符串或双击文件路径,以便interpeter忽略转义序列。使用\t指定原始字符串或r。现在您选择使用的取决于您,但我个人更喜欢原始字符串。

\\