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!
Related
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?
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.
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+')
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!
I am trying to run a python script from the windows command prompt, but I receive the following error message:
"python: can't open file 'pacman.py': [Errno 2] No such file or directory"
when I try the command:
c:\Program Files (x86)\Python27>python pacman.py
This particular python script file pacman.py is located in the following folder:
C:\Users\Chris\Dropbox\edX\CS188x\search
So I added this folder to PYTHONPATH and confirmed that is was there using the following code:
>>> import sys
>>> sys.path
['', 'C:\\Program Files (x86)\\Python27\\Lib\\idlelib', 'C:\\Users\\Chris\\Dropbox\\edX\\CS188x\\search', 'C:\\windows\\syste...
I also checked the permissions on this file:
>>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.W_OK)
True
>>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.R_OK)
True
>>> os.access("C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py",os.X_OK)
True
So I am really not sure why I can't run this file, even though its path has been added to PYTHONPATH. Any help would be greatly appreciated. Thank you.
PYTHONPATH is used by the python interpreter. It is not the same as Windows' PATH environment variable. You can't use it as a search path for passing files to the interpreter on the command line.
So, you need to specify a valid path to the file. Either by using he same command as you've been trying with the difference being your current directory is the same as the location of pacman.py, or by specifying the full path to the file.
did you try running the script from its directory?
i can only guess, but maybe its some issue with the file being located inside your dropbox folder...
python "C:\Users\Chris\Dropbox\edX\CS188x\search\pacman.py"
or
cd C:\Users\Chris\Dropbox\edX\CS188x\search\
"c:\prorgam files (x86)\python27\python" pacman.py
SOLVED! So the comments were right in that I had to change the directory to the location of the file, but what was missing was that I had to edit the system environment variable PATH to include the location of python.exe, which is my case was C:\program files (x86)\python27 but for most people is just C:\python27. Thanks everyone for all your help!