Justin Meltzer
Justin Meltzer

Reputation: 13548

How do you find the filename that you pass to open()?

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

Upvotes: 2

Views: 992

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881575

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.

Upvotes: 2

Wolph
Wolph

Reputation: 80031

Access the name attribute.

fh = open('spam.txt')
print fh.name

Upvotes: 2

Related Questions