Marco_sbt
Marco_sbt

Reputation: 327

How to create a Path from a variable?

I have been running some script in VBA which I like to convert in Python. In VBA I use variables to identify the path from which the raw data are collected so that the same script can be used in any machine. In order to do do so in VBA I identify the path by using the using the following string:

"C:\Users\" & Environ$("username") & "\Data"

Is there a way I can identify in the same way the path in Python?

Upvotes: 1

Views: 1582

Answers (2)

Anna Maria Marcantoni
Anna Maria Marcantoni

Reputation: 104

Just to add to Matthias answer: in case you are looking to use python to "find" a path to the save a file you should keep in mind that despite printing the correct path, Python won't recognize the path unless, after identify the correct Path, you convert it to a string

i.e.: suppose you set your path as a variable

path =  pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv'

then you need to covert path as a string to be used to open/save a file

path1 = str(path)

then you can use path1 to open/save a file

Upvotes: 0

Matthias
Matthias

Reputation: 13232

Use pathlib from the Python Standard Library.

import pathlib
print(pathlib.Path.home() / 'Data')

In older versions of Python (before pathlib) you could use os.path.

import os.path
print(os.path.join(os.path.expanduser('~'), 'Data'))

Some additional info: if you want to reference the path where your script is, you can do that too. You just have to know that __file__ contains the full path to your script.

import pathlib

# full path to the script
print(pathlib.Path(__file__))

# full path to the scripts folder
print(pathlib.Path(__file__).parent)

# full path to the subfolder 'subfolder' in the scripts folder
print(pathlib.Path(__file__).parent / 'subfolder')

# full path to a file in the subfolder
print(pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv')

Upvotes: 5

Related Questions