2014-09-29 106 views
0

我的目標:在當前工作目錄,如果當時一個叫temp文件夾存在刪除,然後創建一個新的,其他人只需創建的文件夾temp。然後將當前工作目錄中輸入的用戶filename複製到新創建的temp文件夾中。無效目錄名稱錯誤

問題:我越來越WindowsError at line 8(shutil.rmtree(temp_path))說明The directory name is invalid

user_file_name = raw_input('Enter the file name:') 

cwd = os.getcwd() 

temp_path = cwd + r'\temp' 

if os.path.exists(temp_path): 
    shutil.rmtree(temp_path) 
    os.makedirs(temp_path) 
else: 
    os.makedirs(temp_path) 

temp_xml_path = temp_path + "\\" + user_file_name 
xml_path = cwd + "\\" + user_file_name 

shutil.copyfile(xml_path, temp_xml_path) 
+3

在創建路徑,請嘗試使用'''os.path.join(temp_path,user_file_name)'' '。 – wnnmaw 2014-09-29 13:02:08

+0

同意@wnnmaw使用['os.path.join'](https://docs.python.org/3/library/os.path.html#os.path.join)創建路徑比使用更安全試圖追加字符串。其他路徑操作也是如此,例如獲取相對路徑,遍歷目錄等。 – CoryKramer 2014-09-29 13:02:53

+2

更具描述性的標題如何? – AndyG 2014-09-29 13:03:11

回答

4

通過使用os.path.join()來創建路徑,可以避免很多潛在的問題。該功能所做的是自動在操作系統之間插入操作系統的路徑分隔符。由於Windows上的分隔符是\,因此可以通過使用它而不是手動字符串連接來讓您的生活更輕鬆。

0

問題的反斜槓。試試做

xml_path.encode("string-escape") 

和temp_xml_path在傳遞給copyfile之前是一樣的。

-1

temp_path是隻有一個\,但最好是使用os.path.join

temp_path = cwd + r'\\temp' 
+0

''你可以提出一個更好的標題便攜式方法的另一個關鍵點'r'\ temp''''工作得很好 – wnnmaw 2014-09-29 13:14:50

+0

的確我錯了r''是一個原始字符串,所以不需要轉義它。 – 2014-09-29 13:17:17