Python pathlib on Windows can't expand user - python

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?

Related

Find the system paths not contained in the environment variable with python

So when I try to find the path from the cmd with where azuredatastudio, I get the path. When I go in Python and do print(os.environ), I get many defined paths, but not this from the upper command in cmd.
How to get in this example azuredatastudio path from Python and where is it stored?
The WHERE command is roughly equivalent to the UNIX 'which' command. By default, the search is done in the current directory and in the PATH.
Source: https://ss64.com/nt/where.html
So you'll have to explicitly look at the paths in the PATH environment variable: os.environ['PATH']. You'll find an implementation in this question here for example: Test if executable exists in Python?
Also, you should be able to just run the command from Python:
from subprocess import check_output
path = check_output(["where", "azuredatastudio"])
print(path)
A easy way to do this is:
import os
os.system("where azuredatastudio")
or if you want to save it in a variable.
import subprocess
process = subprocess.Popen("where azuredatastudio",stdout=subprocess.PIPE)
print(process.stdout.readline())

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.

What path is represented by "../" in python?

In this code:
import scipy.io as scpio
scpio.loadmat('../data/file.mat')
Which path is represented by '../', and how can I print this path?
I am running anaconda, and I assumed that '../' would represent the home directory in parentheses before each anaconda command prompt line, but that guess was incorrect.
You can make use of os.path.realpath
from os import path as op
op.realpath('../')
the ../ usually means the directory above your cwd

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!

How to get Desktop location?

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!

Categories

Resources