tags:

views:

58

answers:

2

I'm trying to open a file with Python, but I'm unsure how to find the correct filename to use.

+1  A: 

Access the name attribute.

fh = open('spam.txt')
print fh.name
WoLpH
This doesn't work for me. I get an error saying the file doesn't exist. Maybe I'm not saving the .txt document in the right place?Plus, I thought filenames typically look like a directory: /music/_singles/kairo.mp3
Justin Meltzer
If you wish to write to a new file you have to use append or write. i.e. `open('spam.txt', 'w')` to create (and empty) the file or `open('spam.txt', 'a')` to create (and append to if it exists) the file.
WoLpH
+2  A: 

You can specify the path to the file in either a complete way (e.g. 'c:/wher/ever/the.txt'), also known as "absolute" because it's taken exactly as you specify it, or a partial one (e.g., just "the.txt", or "ever/the.txt", or "../ever/the.txt", and so on), also known as "relative" because it's taken relatively to the current working directory of your process. If you don't know that working directory, an absolute path is usually simplest to find and specify.

So, find out where the file lives (e.g. c:/wher/ever) and use that absolute path (with "rightside up slashes", instead of windows-style backslashes, as I just explained in another answer) to open the file in question.

Alex Martelli
Psh, more Windows hate :( I still like my `r'C:\paths'` but hate how `r'C:\endsinbackslash\'` fails
Nick T
@Nick, no hate! Just practicality. Even Microsoft's own C compiler accepts "C:/tip/top" as a file path (indeed, that's why it works in Python: by delegating to the underlying C compiler!): C doesn't even _have_ a "raw literal form", of course, so "\t" is _always_ a tab character and "C:\\tip\\top" is the only alternative (it also works in Python, of course, but rightside-up slashes save pixels and screen space, declutter the code, work on all platforms so you can just form the good habit and use it always -- all pluses, so, why not?!).
Alex Martelli
I don't know, force of habit (yes, bad reason). I think one time I had some bug in my code so I made a bunch of changes, `/` -> ` \ ' probably among them, bug went away, so it got buried in my subconscious that they're supposed to be that way :P
Nick T