How to get Desktop location? - python

I'm using Python on Windows and I want a part of my script to copy a file from a certain directory (I know its path) to the Desktop.
I used this:
shutil.copy(txtName, '%HOMEPATH%/desktop')
While txtName is the txt File's name (with full path).
I get the error:
IOError: [Errno 2] No such file or directory: '%HOMEPATH%/DESKTOP'
Any help?
I want the script to work on any computer.

On Unix or Linux:
import os
desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
on Windows:
import os
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
and to add in your command:
shutil.copy(txtName, desktop)

You can use os.environ["HOMEPATH"] to get the path. Right now it's literally trying to find %HOMEPATH%/Desktop without substituting the actual path.
Maybe something like:
shutil.copy(txtName, os.path.join(os.environ["HOMEPATH"], "Desktop"))

This works on both Windows and Linux:
import os
desktop = os.path.expanduser("~/Desktop")
# the above is valid on Windows (after 7) but if you want it in os normalized form:
desktop = os.path.normpath(os.path.expanduser("~/Desktop"))

For 3.5+ you can use pathlib:
import pathlib
desktop = pathlib.Path.home() / 'Desktop'

I can not comment yet, but solutions based on joining location to a user path with 'Desktop' have limited appliance because Desktop could and often is being remapped to a non-system drive.
To get real location a windows registry should be used... or special functions via ctypes like https://stackoverflow.com/a/626927/7273599

All those answers are intrinsecally wrong : they only work for english sessions.
You should check the XDG directories instead of supposing it's always 'Desktop'.
Here's the correct answer: How to get users desktop path in python independent of language install (linux)

Try this:
import os
file1 =os.environ["HOMEPATH"] + "\Desktop\myfile.txt"

Just an addendum to #tpearse accepted answer:
In an embedded environment (c++ programm calling a python environment)
os.path.join(os.environ["HOMEPATH"], "Desktop")
was the only one that worked. Seems like
os.path.expanduser("~/Desktop")
does not return a usable path for the embedded environment (at least not in my one; But some environmental settings in visual studio could be missing in my setup)

Simple and Elegant Try this to access file in Desktop:
import os
import pathlib
import pandas as pd
desktop = pathlib.Path.home() / 'Desktop' / "Panda's" / 'data'
print(desktop) #check you path correct ?
data = pd.read_csv(os.path.joinn(desktop),'survey_results_public.csv')
Congrants!

Related

Clarify how to specify file paths inside Docker coming from Python

I have created a Docker image with for a Flask app. Inside my Flask app, this is how I specify the file paths.
dPath = os.getcwd() + "\\data\\distanceMatrixv2.csv"
This should ideally resolve in a filepath similar to app/data/distanceMatrixv2.csv. This works when I do a py main.py run in the CMD. After making sure I am in the same directory, creating the image and running the Docker image via docker run -it -d -p 5000:5000 flaskapp, it throws me the error below when I try to do any processing.
FileNotFoundError: /backend\data\distanceMatrixv2.csv not found.
I believe this is due to how Docker resolves file paths but I am a bit lost on how to "fix" this. I am using Windows while my Docker image is built with FROM node:lts-alpine.
node:lts-alpine is based on Alpine which is a Linux distro. So your python program runs under Linux and should use Linux file paths, i.e. forward slashes like
dPath = os.getcwd() + "/data/distanceMatrixv2.csv"
It looks like os.getcwd() returns /backend. So the full path becomes /backend/data/distanceMatrixv2.csv.
The os.path library can do this portably across operating systems. If you write this as
import os
import os.path
dPath = os.path.join(os.getcwd(), "data", "distanceMatrixv2.csv")
it will work whether your (Windows) system uses DOS-style backslash-separated paths or your (Linux) system uses Unix-style forward slashes.
Python 3.4 also added a pathlib library, if you prefer a more object-oriented approach. This redefines the Python / division operator to concatenate paths, using the native path separator. So you could also write
from pathlib import Path
dPath = Path.cwd() / "data" / "distanceMatrixv2.csv"

Python pathlib on Windows can't expand user

Expanding "~" using Pathlib gives the wrong path.
from pathlib import Path
ex = Path('~/Documents')
print(ex.expanduser())
I'm expecting "C:\Users{username}\Documents", but instead get "C:\WINDOWS\system32\config\systemprofile\Documents". Is there something wrong with my windows config?
"C:\WINDOWS\system32\config\systemprofile" is the home directory for SYSTEM account. Are you running the script as serivce?

os.makedirs() / os.mkdir() on Windows. No error, but no (visible) folder created

I just try to create some new folders with Python's (3.7.3) os.makedirs() and os mkdir().
Apparently, it works fine because no error occurs (Win 10 Home). But as I try to find the created folder in the windows explorer it isn't there.
Trying to create it again with python I get an error:
'[WinError 183] Cannot create a file when that file already exists:'
Strange thing is, all this worked fine on my computer at work (Wind 10 too), and also on my android tablet.
I've already tried to use relative & absolute paths in makedirs / mkdir.
Ok, it's all about these few lines:
import os
# print(os.getcwd()) shows: C:\Users\Andrej\Desktop
# tried relative path..
os.makedirs('Level1/Level2/Level3')
# tried out some absolute paths like...
os.makedirs('C:/Users/Andrej/Desktop/Level1/Level2/Level3')
os.makedirs('C:\\Users\\Andrej\\Desktop\\Level1\\Level2\\Level3')
UPDATE: It works perfectly when I write makedirs command directly in the Windows powershell. The issue above only occurs when I write this code in Visual Code Studio and then start the file from the powershell by typing in: python makedirs.py...
I just had the same thing happen to me, except I was creating a folder in the AppData/Roaming directory and was using the version of Python from the Microsoft Store.
Apparently, files and directories created in AppData using that version of Python, will instead be created in:
%LocalAppData%\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache
I found what causes this problem finally!
All of the created test folders have been moved to a folder named VTROOT. This folder is created by Comodo Internet Security I use...Its "Auto-Containment" moved all folders I set up by running the code from .py-file (only then) in the PowerShell.
Disabling the auto-containment of Comodo solves the problem..Oh my..
Thank you anyways!
the "if" part will check if the file exists already and consequentially solve the ERROR: '[WinError 183] Cannot create a file when that file already exists:'
the "import sys" part will fix the issue with windows where the folder is created but not visible by the user (even with show hidden files turned on)
import sys
import os
path = 'your path'
def make_dir():
if not os.path.exists(Path):
os.makedirs(Path)
or
import sys
import os
path = 'your path'
def make_dir():
mode = 0o666 #read and write for all users and groups
# form more permission codes search for: *chmod number codes*
if not os.path.exists(Path):
os.mkdir(Path, mode)
Try adding the below import statement:
import sys
This should work.

path to Desktop on Windows without having to know username

I'm use py2exe to create a .exe file so that someone without Python on their computer can run a script. Because I'm creating an alias (shortcut) of the .exe file, I need to hardcode the path to the folder containing the files that the python script targets. I also need to make sure that it will work on anyone's desktop (regardless of username) and work in a folder called Reports. I tried using the following line of code but I got an invalid syntax error:
cwd = r"os.path.expanduser("~/Desktop/Reports")"
I wondered if anyone could provide any advice to help solve this?
Thanks in advance
Maybe this help you
desktop="c:\\users\\{}\\Desktop".format(os.getenv("username"))
This works on my Windows installation:
>>> import os
>>> desktop = os.path.expanduser('~') + '\Desktop'
>>> print(desktop)
C:\Users\MY_USERNAME\Desktop
>>> cwd = os.path.expanduser('~\Desktop\Reports')
>>> print(cwd)
C:\Users\MY_USERNAME\Desktop\Reports
As a standalone script:
import os
import csv2xlsx
cwd = os.path.expanduser('~\Desktop\Reports')
print(cwd)
csv2xlsx.main(cwd + "\Report.csv", cwd + "\Report.xlsx")
Output:
C:\Users\MY_USERNAME\Desktop\Reports
I'm not the best with python, but I know that if you substitute this in your code, you'll get your Desktop directory.
os.environ["HOMEPATH"]
It might not work but substitute it in your code and try it out.
Good luck!

Open a file inside the package directory instead of opening from current directory

I have created a Python package and installed locally. With using the command pip install . .In my package it's necessary to open a file like this.
open('abc.txt','r+')
But my problem is it's try to open the file in the working directory instead of package installed directory.I think absolute path not going to solve my problem.
So my question is, How open a file inside the package ?
NB: While i searched about it saw that os.sys.path may help. But i didn't get any clear solution.
Thank you,
You can try like this:
import os
import inspect
def open_file(filename):
pkg_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
return open(pkg_dir + "/" + filename,'r+')

Categories

Resources