2015-04-02 29 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