Python's driving me mad. Invalid token?

Gary Herron gherron at islandtraining.com
Fri Oct 18 02:59:58 EDT 2002


On Thursday 17 October 2002 11:37 pm, Jim wrote:
> Today I installed Python 2.2.2. I wrote a short script that backs up
> project files, and I'm getting a weird error that I've never gotten
> before. I have spent hours trying to figure this out - can anyone
> help?
>
> My code:

... some code deleted 

> def CopyFiles(dirname,fnamelist):
> 	for name in fnamelist:
> 		destFile = open((dirname+"""\"""+name),'w')
> 		srcFile = open(name,"r")
> 		destFile.write(srcFile.read())
> 		srcFile.close()
> 		destFile.close()
... more code deleted>
> The error:
>
>   File "C:\***\backup.py",
> line 42
>     MainProg()
>              ^
> SyntaxError: invalid token

The problem is that the triple quoted string is not closed (as any
good colorizing editor should be able to show).

The line 

  ..."""\"""+name

starts a string with """ then has a backslashed escaped quote which is
not counted as a closing quote because of the backslash, then two
quotes which is not enough to close the triple-quoted string.  The
intererter continues to the end of the file looking for a triple
quote, and produces the error when none is found.


If you want a string with a backslash, try '\\' or "\\".  Better yet,
to create a file path from component parts, use the function 'join'
from the os.path module.  This does the right thing on any OS so your
program is os independent.

Try:
  import os
  ...
  pathname = os.path.join(dirname, name)
  destFile = open(pathname,'w')	

Gary Herron
gherron at islandtraining.com





More information about the Python-list mailing list