[Tutor] adding together strings
Fri, 7 Apr 2000 08:02:02 -0700
> Hello python tutors,
> I hope you can help me with a little problem. (I am a beginner).
> I am working on a program which will access some files in a folder on the
> desktop without me having to type in the whole address every time.
> Here is what I would like to do.
> filename = raw_input("type name of file ")
> filename="C:\windows\desktop\targetfolder\" + filename
> When I try this kind of thing at the command line it works fine, but when I
> put it into a module it tells me that "filename" is an "invalid token"
I'm suprised it works at the command line - you have a problem here with
Python's rules for escaping special characters in strings. The primary
problem is that the \ before the final " on the second line escapes the ",
so that Python thinks of it as being a quote within the string rather than
the quote that ends the string.
Similarly, although you may not have noticed it, the \t in \targetfolder
gets turned into a tab.
You can fix this immediately by something like:
filename = raw_input("type name of file ")
filename="C:\\windows\\desktop\\targetfolder\\" + filename
In other words, in regular strings in Python, whenevr you want a "\" you
should type a "\\".
A better solution to your problem, because it will be breeding good habits
for the future, is to use the os.path module's functions, particularly
os.path.join. This will help if you ever have to work with unix or mac
systems in python; and means you don't have to work with all those double
backslashes on your system.
Hope this helps.