alwbtc
alwbtc

Reputation: 29465

How do I enter file path in built-in open() function?

I have read the docs but it doesn't tell how we enter the file path in open() function.

If file path is:

/opt/myapp/report/sample.txt 

or

$MYPATH/report/sample.txt (where $MYPATH=/opt/myapp)

Is it ok to write the statement this way:

f = open('/opt/myapp/report/sample.txt', "r")

or

f = open('$MYPATH/report/sample.txt', "r")

Upvotes: 0

Views: 1019

Answers (2)

khagler
khagler

Reputation: 4056

You can use os.environ to get the value of an environment variable, and os.path.join to combine it with the report/sample.txt part:

os.path.join(os.environ['MYPATH'], 'report/sample.txt')

The absolute path will also work.

Upvotes: 1

Gareth Latty
Gareth Latty

Reputation: 89057

What you want to do here is expand the environment variables in the path, which can be done with os.path.expandvars():

Return the argument with environment variables expanded. Substrings of the form $name or ${name} are replaced by the value of environment variable name. Malformed variable names and references to non-existing variables are left unchanged.

On Windows, %name% expansions are supported in addition to $name and ${name}.

E.g:

with open(os.path.expandvars(path), "r") as f:
    ...

Note my use of the with statement here, which is the best way to open files, as it ensures they are closed correctly, even when there is an exception, and reads nicely.

Upvotes: 5

Related Questions