Write to any users desktop in Python - python

Im new to Python so apologies if this is a basic question.
I have successfully created an exe file that writes to my specific desktop directory, but I am struggling to find a way to write to any users desktop directory.
The idea being my exe file can be copied onto any user profile and work the same.
Here is my code:
file = open('C:\\Users\\user\\Desktop\\PC info.txt','w')
Could somebody help me adjust my code to work on any users desktop. Thank you in advance

You can get the username with the os module:
import os
username = os.getlogin() # Fetch username
file = open(f'C:\\Users\\{username}\\Desktop\\PC info.txt','w')
file.write('Hello desktop')
file.close()

You could use os.getlogin with an f-string to insert the username to the file path:
import os
with open(fr'C:\Users\{os.getlogin()}\Desktop\PC info.txt', 'w') as f:
# do something with f
But, a much better cleaner way nowadays would be to use pathlib:
import pathlib
with open(pathlib.Path.home() / "Desktop/PC info.txt", "w"):
# do something with f
Also, it's always advisable to use a context manager (with open(...) as f) to handle files, so that the filehandler gets closed even if an exception occurs.

If you are using Python3.5+, you can use the following to get the path to the current user's home directory:
import os
import sys
from pathlib import Path
def main():
home = str(Path.home())
path = os.path.join(home, "filename.txt")
with open(path, "w") as f:
f.write("HelloWorld")
if __name__ == '__main__':
main()

Is this what you are looking for?
username = "MrShaun"
filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username)
file = open(filename, 'w')
In this example, filename would be: "C:\Users\MrShaun\Desktop\PC info.txt"
Obviously, you would probably want to build a structure around it, for example asking the user for input of a username and assigning that to the variable username.
Read more about formatting strings in Python here

Related

Is there a way to execute a file knowing only the subdirectory?

I have two exe files located at
C:\Users\Bella\Desktop\Folder\fuctions
I want to write a python script that would open them both from Desktop\Folder, The issue is I want to share this script with people and I won't know the name of their User,
Is there a way to execute the files while only knowing it will be in Folder\functions since I will always know that my script will be located in "Folder"
import os
os.startfile(r"C:\Users\Bella\Desktop\Folder\Dist\fuctions\Test.exe")
os.startfile(r"C:\Users\Bella\Desktop\Folder\Dist\fuctions\Test2.exe")
obviously that wont work when shared to friends
You can use relative path as mentioned in the comments or use:
import os
# get the directory of the file
dir = os.path.realpath('...')
# append the remainder of the path
path = os.path.join(dir, 'Dist\fuctions\Test.exe')
Use os.environ.get("USERNAME")
It gets the username of the user.
import os
username = os.environ.get("USERNAME")
os.startfile(f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test.exe")
os.startfile(r=f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test2.exe")
Or you can use os.getlogin()
import os
username = os.getlogin()
os.startfile(f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test.exe")
os.startfile(r=f"C:\\Users\\{username}\\Desktop\\Folder\\Dist\\fuctions\\Test2.exe")
Upvote if it works :)

Saving Python .txt file to user's desktop without stating my user name in code

I'd like to create a .txt file which will be saved to the desktop of whoever's running this code. My current solution specifies the path to my own particular desktop and includes my username. How should I modify the code so that it works with any user?
filename = open('c:/Users/my_username/Desktop/filename.txt', 'w')
You can use os.path.expanduser('~') for a platform independent way of automatically expanding a user's home directory, so in practice it might look like:
with open(
os.path.join(os.path.expanduser('~'), 'Desktop', 'filename.txt'), 'w'
) as fh:
# do things
C.Nivs provides an excellent Answer, but what if the Desktop is not located in the home directory? my current Work and Home desktop, both running Windows 10 have the Desktop nested under OneDrive or DropBox.
Lets look at a possible solution using Pathlib using the relative_to method to measure the distance from the home directory and return the minimum. We will use a recursive method to look over our directory and search for a Desktop Match.
In Action
path_finder()
out:
WindowsPath('C:/Users/datanovice/OneDrive/Desktop')
The dictionary it self will look like this :
{WindowsPath('C:/Users/datanovice/anaconda3/Library/qml/QtQuick/Controls/Styles/Desktop'): 7,
WindowsPath('C:/Users/datanovice/anaconda3/pkgs/qt-5.9.7-vc14h73c81de_0/Library/qml/QtQuick/Controls/Styles/Desktop'): 9,
WindowsPath('C:/Users/datanovice/AppData/Local/Microsoft/PlayReady/Internet Explorer/Desktop'): 6,
WindowsPath('C:/Users/datanovice/AppData/Local/Microsoft/PlayReady/Internet Explorer/InPrivate/Desktop'): 7,
WindowsPath('C:/Users/datanovice/OneDrive/Desktop'): 2}
For your use case it will be similair to C.Nivs solution:
with open(
pathfinder().joinpath('filename.txt'), 'w'
) as fh:
Function & Module.
from pathlib import Path
def path_finder(directory=Path.home()):
path_finder_dict = {}
for child in Path.home().rglob('*'):
if child.name == 'Desktop':
distance = len(child.relative_to(Path.home()).parts)
path_finder_dict[child] = distance
return min(path_finder_dict, key=path_finder_dict.get)
You can do this using the getpass library which gets the current active user, then replace this with the username:
import getpass
filename = open('C:/Users/'+getpass.getuser()+'/Desktop/filename.txt', 'w')
you can use the expanduser method in os.path...
os.path.expanduser('[username you want]')

Relative Addressing in Python

I have been given a Project on Python Programming so I wanted to ask you that how can I give relative directory paths to the generated files in Python so that it could be opened in other machines as absolute paths won't work on every PC
If you have write access to the folder containing your script then you can use something like
import sys, os
if __name__ == '__main__':
myself = sys.argv[0]
else:
myself = __file__
myself = os.path.abspath(myself)
whereami = os.path.dirname(myself)
print(myself)
print(whereami)
datadir = os.path.join(whereami, 'data')
if not os.path.exists(datadir):
os.mkdir(datadir)
datafile = os.path.join(datadir, 'foo.txt')
with open(datafile, 'w') as f:
f.write('Hello, World!\n')
with open(datafile) as f:
print(f.read())
In the file that has the script, you want to do something like this:
import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')
This will give you the absolute path to the file you're looking for, irrespective of the machine you are running your code on.
You can also refer these links for more information:
Link1
Link2
For more specific information, please make your question specific. i.e Please post the code that you have tried along with your inputs and expected outputs.

How to fix error trying to find user files in Python?

I made this script to copy this file to any user's Documents folder:
import getpass
import os
user = getpass.getuser() #gets username
file = "try.py" #file to copy
new_file = "C:\\Users\\", user,"\\Documents\\try.py" #folder in which the file shoud copy
os.rename(file, new_file) #copy the file
The problem is, when I try to run it, IDLE show this error:
I don't really understand what it means. Please note that I am a beginner in Python.
new_file is not a concatenated string but a tuple.
Try using this for concatenation of strings
new_file = "C:\\Users\\" + user + "\\Documents\\try.py"

Creating a python file in a local directory

Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
using python 3.3
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
use open:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f

Categories

Resources