2015-04-02 37 views
0

我正在學習python,並被困在一個教程上,只要指南應該工作,但不是,我已經看到類似的問題,但不能理解它們如何應用於我所遵循的代碼,代碼在最後一行結尾處失敗。Python串聯錯誤

import os 
import time 

source = ["'C:\Users\Administrator\myfile\myfile 1'"] 

target_dir = ['C:\Users\Administrator\myfile'] 

target = target_dir + os.sep + \ 
     time.strftime('%Y%m%d%H%M%S') + '.zip' 

can only concatenate list (not "str") to list 

我一直在使用.append並通過添加[]和()到+「的.zip」,但都無濟於事改變代碼嘗試了一些方法,所以我希望有人可以解釋爲什麼它的失敗以及我如何糾正它。

我使用的Python 2.7.9在Windows

感謝

+0

您使用的是什麼教程? – Kevin 2015-04-02 17:09:43

+1

爲什麼'source'和'target_dir'列表? – 2015-04-02 17:10:33

+0

我不確定這只是教程是如何編碼的,教程是用於備份腳本的,教程是swaroop的一個python字節 – Ambush 2015-04-02 17:15:13

回答

4

target_dir不應使用方括號創建。

target_dir = 'C:\Users\Administrator\myfile' 

target = target_dir + os.sep + \ 
     time.strftime('%Y%m%d%H%M%S') + '.zip' 

順便說一下,照顧你的反斜槓,因爲他們也用在一個字符串來表示特殊字符。例如,"c:\new_directory"將被解釋爲「C冒號換行符W ...」而不是「C冒號反斜槓N W ...」。在這種情況下,你需要轉義"c:\\new_directory"的削減自己,或使用原始字符串像r"c:\new_directory",或定期斜槓(如果您的操作系統允許作爲路徑分隔符)像"c:/new_directory"

+1

根據文檔源需要雙引號如果目錄名稱中有空格,但也嘗試用單引號並且仍然沒有去 – Ambush 2015-04-02 17:13:39

+0

更好的是'target = os.path.join(target_dir,time.strftime('%Y%m%d%H%M%S')+'.zip')' – 2015-04-02 17:13:47

+1

@ YK2,源'需要雙引號真的取決於你在做什麼。例如,如果你將它傳遞給'os.system'調用,你可能需要它。但是一般地說「如果Python字符串包含空格,它總是需要雙引號」,這是不正確的。你指的是什麼文件? – Kevin 2015-04-02 17:17:27

2

TARGET_DIR是一個列表,所以在你的榜樣,你需要做的:

target = target_dir[0] + os.sep + \ 
     time.strftime('%Y%m%dT%H%M%S') + '.zip' 

您將看到錯誤,因爲你是試圖添加一個列表(target_list)和字符串,蘋果和橘子。

+0

這個 – Ambush 2015-04-02 17:23:52

+0

@ YK2也不知道這意味着什麼。 – 2015-04-02 17:25:09

+0

我的意思是你建議的代碼 – Ambush 2015-04-02 17:28:45

4

您應該使用os.path.join(),使正確的平臺將始終使用特定的目錄分隔符

import os 
import time 

source = "C:\Users\Administrator\myfile\myfile 1" 

target_dir = "C:\Users\Administrator\myfile" 

target = os.path.join(target_dir, time.strftime('%Y%m%d%H%M%S') + '.zip') 
+0

這在這種情況下不起作用 – Ambush 2015-04-02 17:23:37

+0

@ YK2你的電腦爆炸了嗎?猴子飛出屏幕嗎?房子融化了嗎? 「這不起作用」是什麼意思? – 2015-04-02 17:24:29

+0

您建議的代碼 – Ambush 2015-04-02 17:28:22