Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I put a variable in a path

I’m trying to store a path in a variable. see below

target = r"C:\Users\User\CodeProjects\WebSafer"

However, I need it to be dynamic. Not hardcoded to my username, so I get the login username by doing:

val = os.getlogin()

So I need to put the variable val in the path. But every time I tried doing it I always get a truncating/syntax error. Please help me! Below is the code snippet:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print("No copy found...making a copy\n")

val = os.getlogin()

original = r"C:\*******\********\*******\***\****"
target = r"C:\Users\User\CodeProjects\WebSafer"
shutil.copy(original, target)

The "*" are just for privacy reasons, there actually replaced with the right path location to what I’m copying.

What I have tried so far:

target = r"C:\Users\{val}\CodeProjects\WebSafer".format(val = os.getlogin)
target = r"C:\Users\{}\CodeProjects\WebSafer".format(val)
target = rf"C:\Users\{val}\CodeProjects\WebSafer".format(val = os.getlogin)
target = rf"C:\Users\{}\CodeProjects\WebSafer".format(val)

>Solution :

Don’t mix f with .format, this is working for me:

import os

val = os.getlogin()
print(rf"C:\Users\{val}\CodeProjects\WebSafer")

And I think better way is:

import os.path
from pathlib import Path

home = str(Path.home())
print(os.path.join(home, "CodeProjects\WebSafer"))

Then if you encounter some error when copying, you need clarify what you want to copy, copy a file, or a folder, if a folder, should it go to within the dest folder, or overwrite dest folder?
You may want try different methods such as
shutil.copy, shutil.copytree, and different parameters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading