复制文件引发的语法错误无法解码字节

2024-09-19 23:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个简短的程序,它可以在每次运行文件夹时对其进行备份。现在是这样的:

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)

但是我得到一个错误:

^{pr2}$

我不知道为什么(根据文档,我认为我的代码写得很好)

我怎样才能更好地解决这个问题?在


Tags: import程序文件夹worlddatetimeos备份
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"..."使其成为原始字符串。在

^{pr2}$

但是,不要同时做这两件事,否则他们会被逃脱两次:

^{3}$

只有在直接在源代码中输入路径时,才需要对它们进行转义;如果从文件、用户输入或某些库函数中读取这些路径,它们将自动转义。在

反斜杠用于转义字符,因此当解释器在文件路径字符串中看到\时,它会尝试将它们用作转义字符(类似于\n表示新行,\t表示制表符)。在

有两种方法可以解决这个问题,使用原始字符串或双斜杠文件路径,这样interpeter就会忽略转义序列。使用r指定原始字符串或\\。现在你选择使用哪一个是由你自己决定的,但我个人更喜欢原始字符串。在

#with raw strings
shutil.copy2(r"C:\Users\joaop\Desktop\VanillaServer\world",r"C:\Users\joaop\Desktop\VanillaServer\Backups")

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

#with double slashes
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)

相关问题 更多 >