2017-02-10 46 views
0

我試圖編寫一個簡短的程序,只要我運行它就可以備份文件夾。目前,它是這樣的:複製文件引發了SyntaxError無法解碼的字節

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

你或許應該逃避反斜槓或使用原始字符串:「 」C:\\用戶...「'或'R 」C:\用戶...「' –

+1

......或者用斜線。 – cdarke

+0

[(unicode錯誤)'unicodeescape'編解碼器可能重複無法解碼位置2-3中的字節:截斷\ UXXXXXXXX轉義](http://stackoverflow.com/questions/37400974/unicode-error-unicodeescape-codec-斜面解碼字節-在位-2-3-trunca) –

回答

0

斜線用於轉義字符所以在翻譯時看到\在你的文件路徑字符串時,它會嘗試使用它們作爲轉義字符(這是類似的東西爲\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' 

你只需要直接在源進入路徑時躲開他們。如果您從文件,用戶輸入或某些庫函數中讀取這些路徑,它們將自動被轉義。

相關問題