Reputation: 300
Hi I already know how to open a file in python 3 but is there a way of opening a file in C:\Users\user\Documents (user is the user of the logged in computer). So I want to open a text file in any users Documents named something e.g. test.txt This file maybe on 3 computers and I want to open the file with the same name in many logons.
This is how you would normally open a file in python:
file = open("C:\Users\Rohit\Documents\text.txt", "r+")
file.close()
So is there a way to replace 'Rohit' with the user logged on e.g. Robert, Adam, Lewis, etc.
Upvotes: 0
Views: 1106
Reputation: 649
Yes, you can use os
to get the username.
import os
os.environ.get("USERNAME")
or
os.getlogin()
How to Retrieve name of current Windows User (AD or local) using Python?
Or, as described by R. Mitchum, you can bypass getting the user name explicitly
os.path.expanduser("~\Documents\\text.txt")
will get you the filepath to text.txt
for the current user:
C:\\Users\\CURRENTUSER\\Documents\\text.txt
Upvotes: 2
Reputation: 465
I don't use Windows, but according to os.path's documentation you should be able to do something like this:
file = open(expanduser("~\Documents\text.txt"), "r+")
Upvotes: 1