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
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?
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())
I have a script which has an error because 'neato.exe' can't be found in paths. When I look at os.environ["PATH"], indeed C:\\Program Files (x86)\\Graphviz2.38\\bin, the path to neato.exe, is not there. I can do a hack for the time being by adding this line, but this doesn't seem satisfactory.
if not 'C:\\Program Files (x86)\\Graphviz2.38\\bin' in os.environ["PATH"]:
os.environ["PATH"] += os.pathsep + 'C:\\Program Files (x86)\\Graphviz2.38\\bin'
Nonetheless, it shows that the error ValueError("Program %s not found in path." neato.exe) is an accurate error. The script works when I add the path to Neato. I added C:\Program Files (x86)\Graphviz2.38\bin to my Environmental Variables in windows, but to no avail. And I also noticed that there are only a few paths in my Path Env. Vars., not the many that python lists. I am using python 3.7 and also running it using the anaconda navigator. I would like to make a more permanent change so I don't have to edit every script that looks for neato.exe with the silly if statement above. Does anyone know how to change what's in os.environ["PATH"] in anaconda?
I am using networkx, networkx.drawing.nx_agraph.to_agraph. The script agraph.py has this function (_which()), which need to make a path match or it will throw an error.
def _which(self, name):
"""Searches for name in exec path and returns full path"""
import os
import glob
paths = os.environ["PATH"]
if os.name == "nt":
exe = ".exe"
else:
exe = ""
for path in paths.split(os.pathsep):
match = glob.glob(os.path.join(path, name + exe))
if match:
return match[0]
raise ValueError("No prog %s in path." % name)
A few things to note about Windows Path:
Windows Path is a combination of user defined and system defined - the former is appended to the latter
Windows Path has a pretty short length limit
Unfortunately because of the above, you'll probably want to temporarily change the Path for your program to ensure it can find the binary you're looking for.
You could set the PATH environment variable with the Graphviz bin directory at the beginning before executing your script(s).
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!
Working on OS X Lion, I'm trying to open a file in my python-program from anywhere in the terminal. I have set the following function in my .bash_profile:
function testprogram() {python ~/.folder/.testprogram.py}
This way I can(in the terminal) run my testprogram from a different directory than my ~/.
Now, if I'm in my home directory, and run the program, the following would work
infile = open("folder2/test.txt", "r+")
However, if I'm in a different directory from my home-folder and write "testprogram" in the terminal, the program starts but is unable to find the file test.txt.
Is there any way to always have python open the file from the same location unaffected of where i run the program from?
If you want to make it multiplatform I would recommend
import os
open(os.path.join(os.path.expanduser('~'),'rest/of/path/to.file'))
Use the tilde to represent the home folder, just as you would in the .bash_profile, and use os.path.expanduser.
import os
infile = open(os.path.expanduser("~/folder2/test.txt"), "r+")
This is no different than referring to a file via anything else besides Python, you need to use an absolute path rather than a relative one.
If you'd like to refer to files relative to the location of the script, you can also use the __file__ attribute in your module to get the location of the currently running module.
Also, rather than using a shell function, just give your script a shebang line (#!/usr/bin/env python), chmod +x it, and put it someplace on your PATH.
You could simply run the function in a subshell so you can cd home before running it:
function testprogram() { (
cd && python .folder/.testprogram.py
) }
In python sys.argv[0] will be set to the path of the script (if known). You can use this plus the functions in os.path to access files relative to the directory containing the script. For example
import sys, os.path
script_path = sys.argv[0]
script_dir = os.path.dirname(script_path)
def script_relative(filename):
return os.path.join(script_dir, filename)
infile = open(script_relative("folder2/test.txt"), "r+")
David Robinson points out that sys.argv[0] may not be a full pathname. Instead of using sys.argv[0] you can use __file__ if this is the case.
Use either full path like
/path/to/my/folder2/test.txt
or abbreviated one
~/folder2/test.txt