PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 20, 2022

[FIXED] How do I put a variable in a path

 December 20, 2022     python, shutil, syntax     No comments   

Issue

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

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.



Answered By - Lei Yang
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing