Home > Software design >  How to move a file with python, using %username% in destination path
How to move a file with python, using %username% in destination path

Time:04-25

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.

CodePudding user response:

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"

CodePudding user response:

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"
  • Related