复制文件提出了一个SyntaxError不能解码字节

问题描述 投票:0回答:2

我想编写一个简短的程序,使得每当我运行一个文件夹的备份。目前,它是这样的:

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 

我想不通为什么(根据文件,我觉得我的代码编写正确)

我怎样才能解决这个问题/做一个更好的办法?

python python-3.x
2个回答
1
投票

反斜杠用于转义字符所以在翻译时看到\在你的文件路径字符串时,它会尝试使用它们作为转义字符(这是类似的东西为\n新的生产线和\t制表符)。

有2种方式解决这个问题,通过削减你的文件路径,以便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)

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'

你只需要直接在源进入路径时躲开他们。如果你从文件中读取这些路径,从用户的输入,或者从一些库函数,它们会自动进行转义。

© www.soinside.com 2019 - 2024. All rights reserved.