Trouble opening files

Tim Roberts timr at probo.com
Sun Jan 29 23:33:52 EST 2006


"Westbrook, Christopher L (WESTBCL04)" <WESTBCL04 at juniata.edu> wrote:
>
>I am having some trouble, and I can't figure out why.  

...

>form = cgi.FieldStorage()
>print "Content-type:text/html\n\n";
>filename = form["file"].value+".txt" #all files end in .txt extension
>
>filename = filename.replace("\\","\\\\")

This line is incorrect.  Backslashes are only treated as escape characters
when they are LITERAL strings in a Python source file.  When you're reading
a filename from some outside source like this, the string will already
contain the correct characters.

What you'll end up with is literally double backslashes.  For example, if
you read a variable containing c:\tmp\new.txt, you will end up with
c:\\tmp\\new.txt, AS IF you had given the literal string
"c:\\\\tmp\\\\new.txt".

Fortunately, most Win32 APIs will ignore double-backslashes, but it isn't
right.  And, they are guaranteed not to work if they are the first
characters of the filename.

>#print filename
>
>f = file(filename,'\r') #open file for reading

Where did you get that?  \r is a carriage return.  You need a letter "r":

    f = file(filename, 'r')
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list