0

I would like to open and work with a file with Python however I would like to use Windows %systemdrive% when referring to a file instead of full path. This piece of code works:

if not os.path.isfile('C:\\Work\\test\sample.txt'):

This does not:

if not os.path.isfile('%systemdrive%\\Work\\test\\sample.txt'):

Any idea? Thank you in advance!

2 Answers 2

3

There is a dedicated function for solving this problem named 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}.

if not os.path.isfile(os.path.expandvars('%systemdrive%\\Work\\test\\sample.txt')):
    pass  # do something
Sign up to request clarification or add additional context in comments.

2 Comments

@Michel consider accepting an answer if it was helpful.
I woudl do but as per the help: 1 Choose one answer that you believe is the best solution to your problem. 2 To mark an answer as accepted, click on the check mark beside the answer to toggle it from greyed out to filled in. 3 You may change which answer is accepted, or simply un-accept the answer, at any time. I cannot find point 2....
1

You can use os.environ

import os
import os.path
fn = r'{0}\Work\test\sample.txt'.format( os.environ['systemdrive'] )
if not os.path.isfile(fn):
    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.