pythonsyntaxshutil

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:

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
    
    print(Path.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.