Ambush
Ambush

Reputation: 125

Python Concatenation Error

I am learning python and am stuck on a tutorial which as far as the guide goes should be working but isn't, i have seen similar questions asked but cant understand how they apply to the code i am following, the code fails at the end of the last line.

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

i have tried some methods using .append and also changing the code by adding [] and () to the + '.zip' but all to no avail, so i was hoping someone could explain why its failing and how i correct it.

i am using python 2.7.9 on windows

thanks

Upvotes: 0

Views: 221

Answers (3)

Kevin
Kevin

Reputation: 76194

target_dir should not be created with brackets.

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

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

Incidentally, take care with your backslashes, because they are also used to signify special characters in a string. For example, "c:\new_directory" would be interpreted as "C colon newline W..." rather than "C colon backslash N W...". In which case you would need to escape the slash yourself with "c:\\new_directory", or use raw strings like r"c:\new_directory", or regular slashes (if your OS allows that as a path separator) like "c:/new_directory"

Upvotes: 4

ILostMySpoon
ILostMySpoon

Reputation: 2409

You should use os.path.join() so that the correct platform-specific directory separator will always be used

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')

Upvotes: 4

reptilicus
reptilicus

Reputation: 10397

target_dir is a list, so in your example you need to do:

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

You see that error because you are trying to add a list (target_list) and strings together, apples and oranges.

Upvotes: 2

Related Questions