'How to move a file with python, using %username% in destination path
I can't manage to make this code work
import os
source = "juan.txt"
destination = "C:\\Users\\%username%\\Desktop\\juan.txt"
try:
if os.path.exists(destination):
print("There is already a file there")
else:
os.replace(source, destination)
print(source, "was moved")
except FileNotFoundError:
print("File not found")
When I change %username% to my actual username it works, but I really need code that will allow me to replace this placeholder with the same value without the user knowing it.
Solution 1:[1]
I think what you're looking for is getting the user login name. You can do it this way:
username = os.getlogin()
destination = "C:\\Users\\" + username + "\\Desktop\\juan.txt"
Solution 2:[2]
u can use format:
destination = "C:\\Users\\{}\\Desktop\\juan.txt"
...
destination.format(myvar)
or in python 3.6 +
destination = f"C:\\Users\\{myvar}\\Desktop\\juan.txt"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Constantin Guidon |
