0

I want to open a file in the desktop, or anywhere else in the C:/Users/USERNAME/ directory. but I don't know what the code to get the username is. for example, in batch-file programming I could use:]

c:/Users/%USERNAME%/...

I want to use it in the open function. I have tried both:

open('C:/Users/%%USERNAME/Desktop/data3.txt')

open('C:/Users/%USERNAME%/Desktop/data3.txt')

I know there should be an import that can give the username to my code. But I don't know what it is. And I also would like to know if I can use the username like %USERNAME% or %%USERNAME or a single thing that doesn't need any import.

Ariocodes
  • 13
  • 5
  • Since the desktop directory is under home directory for all systems you better get the home directory and append the desktop. Sometimes user name and home directory name may differ. https://stackoverflow.com/a/4028943/2681662 – MSH Jul 27 '21 at 13:18

2 Answers2

1

Three ways to do this using the os module:

  1. Use os.getlogin():
import os
>>> os.path.join("C:", os.sep, "Users", os.getlogin(), "Desktop")
'C:\\Users\\your_username\\Desktop'
  1. Use os.environ():
>>> os.path.join(os.environ['userprofile'], "Desktop")
'C:\\Users\\your_username\\Desktop'
  1. Use os.path.exapndvars():
>>> os.path.join(os.path.expandvars("%userprofile%"), "Desktop")
'C:\\Users\\your_username\\Desktop'
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • f-strings for python 3: `open(f'C:/Users/{os.getlogin()}/Desktop/data3.txt'')` – It_is_Chris Jul 27 '21 at 13:18
  • @It_is_Chris - It's recommended to use `os.path.join` while concatenating file paths. See [here](https://stackoverflow.com/questions/13944387/why-use-os-path-join-over-string-concatenation) – not_speshal Jul 27 '21 at 13:19
0

you can use expanduser and ~ for that :

import os

open(os.path.expanduser('~\\Desktop\\data3.txt'))

or if you want to use os.path.join :

open(os.path.join(os.path.expanduser('~'), 'Desktop', 'data3.txt'))
patate1684
  • 639
  • 3
  • 17