我正在尝试编写一个简短的程序,它可以在每次运行文件夹时对其进行备份。现在是这样的:
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}$我不知道为什么(根据文档,我认为我的代码写得很好)
我怎样才能更好地解决这个问题?在
在Python中,
\u...
表示Unicode序列,因此您的\Users
目录被解释为Unicode字符,但并不十分成功。在要修复它,您应该将不同的
^{pr2}$\
转义为\\
,或者使用r"..."
使其成为原始字符串。在但是,不要同时做这两件事,否则他们会被逃脱两次:
^{3}$只有在直接在源代码中输入路径时,才需要对它们进行转义;如果从文件、用户输入或某些库函数中读取这些路径,它们将自动转义。在
反斜杠用于转义字符,因此当解释器在文件路径字符串中看到
\
时,它会尝试将它们用作转义字符(类似于\n
表示新行,\t
表示制表符)。在有两种方法可以解决这个问题,使用原始字符串或双斜杠文件路径,这样interpeter就会忽略转义序列。使用
r
指定原始字符串或\\
。现在你选择使用哪一个是由你自己决定的,但我个人更喜欢原始字符串。在相关问题 更多 >
编程相关推荐