How set a defaut working directory in python? - python

I would like to change the defaut working directory in python on windows. I mean the default path is c:/users/usename and every time you start python you need to do
import os
os.chdir(path)
to modify it.
I would like to know if there is a way to set new directory by defaut?
For exemple with R we can do that by editing Rprofile file. But for python I don't know (i don't find) if there is this type of file.
Thank you in advance
Stéphane

You can use pathlib.
Python uses environment variables of your os. Therefore you have to adjusted your %PATH% to get what you would like to do.
import pathlib
current_dir = pathlib.Path()
print(current_dir.pwd)
output: the directory where you started your script

Well, there is no way of permanently changing the default working directory in Python that I am aware of.
But, there are some things you can do like:
If you are launching Python from the start menu of Windows, right-click on the icon and select more > file location.
Once there you can right-click on the shortcut and select properties. From there you should be able to define the Start In location.
This could be one way to change your default directory.
Hope this answer helps you.

Related

My modules can not be found

I would like to import some functions I regularly use into my scripts, instead of having to paste them in it.
This is the reading I get when I check with the path browser:
>>> sys.path
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\Lib\idlelib
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\python37.zip
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\DLLs
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\lib
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\lib\sitepackages
I'd like to permanently add the following path to it:
C:\Users\Apex\AppData\Local\Programs\Python\Python37-32\PythonScripts
I've tried the following:
path = 'C:/Users/Apex/AppData/Local/Programs/Python/Python37-32/PythonScripts'
import sys, os
sys.path.append(path)
All the paths above and the one I want to add appear in the shell, but when I check the path browser, mine isn't there.
How can I set PythonScripts to Python's path permanently?
I read up a bit on PYTHONPATH, but I didn't understand how to use it.
Please, when you reply, don't I assume I might know everything you do. Thanks.
I'm using window 7 with Python v3.7.0
Just in case that this might help someone else, this is what worked for me:
I moved the PythonScripts folder out of the Python37-32 and into the Apex folder, and I added the path to it and to another folder to the Windows Environment Viariables like this:
Variable name: PYTHONPATH
Variable value: C:\Users\Apex\PythonScripts;C:\xampp\htdocs\PythonScripts
The suggestion given in the posting I was pointed to of using:
C:\Python27
did not work for me.
Thanks to all for their valuable input.

Set working directory in Python / Spyder so that it's reproducible

Coming from R, using setwd to change the directory is a big no-no against reproducibility because others do not have the same directory structure as mine. Hence, it's recommended to use relative path from the location of the script.
IDEs slightly complicate this because they set their own working directory. In Rstudio, I can easily get around this problem with Rstudio's projects, setting the project's directory to be my script folder.
With Python and Spyder, there doesn't seem to be any solution. Spyder does not have a feature like Rstudio's project. Setting the directory to the script's location does not work while doing interactive analysis (since __file__ is not available).
What to do so that the working directory in Python / Spyder is reproducible?
To do this automatically, put this at the beginning of your script:
from os import chdir, getcwd
wd=getcwd()
chdir(wd)
In the interim, you can use os.chdir
import os
os.chdir('C:\Users\me\Documents')
It appears they did consider this as a feature in Spyder based on this GitHub ticket, but it is still waiting implementation as of mid-May:
We could add an option to the Run dialog to automatically set the
working directory to the one your script is being ran.
However, someone else will have to implement it. We're pretty busy
with other things at the moment, sorry.
https://github.com/spyder-ide/spyder/issues/3154
#ccordoba12 ccordoba12 added this to the wishlist milestone on May 14
as I wrote here, Mark8888 pointed out to run the whole script (run file (F5)) instead of just pieces of the script
this way multiple approaches should work to get the script file location and change the current working directory
import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())
also
import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
Well, there are a lot of things that you can try!
1. Change the directory to the current directory in the toolbar.
2. Change the Global directory to the current directory in Preferences>Global Working Directory. Click 'the current file directory' radio button.
Hope it helps!
I tried this and it works.
import os
abspath = os.path.abspath('') ## String which contains absolute path to the script file
os.chdir(abspath) ## Setting up working directory

How to change the default working directory in python

I have a quick question about the default working directly on python.
I am currently using the python 2.7. In this case the default working directly is the C:/Python27.
I want to change this permanently to another directory.
Even if we write down following on shell, the default working directory will go back to the original C:/Python27 automatically.
import os
os.chdir('a path')
Does any one know how to set up default directory permanently to "the path" which keeps the directory after the closing the shell?
This is a different question from how to change working directory just by the function temporarily.
Thank you so much for your help!!
The working directory of the python directory is the directory from which it was started. If from a console (cmd.exe) I do cd /some/dir and then start python, its working directory will be /some/dir.
If you want an interactive console started at a given directory you have some options:
Using a shortcut, you can change its Start in field, in the properties tab, to point to your target directory.
Use IPython instead, and add a startup script to the default profile so it always start at the target directory. IPython is an enhanced interactive with lots of useful features.
If you are running from a script and want to switch to the folder where you script is stored, you could use os.cd(os.path.dirname(__file__)).
If you are launching Python from the start menu of Windows, right click on the icon and select more -> file location.
Once there you can right click on the shortcut and select properties. From there you should be able to define the 'Start in:' location.

Add a directory to Python sys.path so that it's included each time I use Python

Currently, when trying to reference some library code, I'm doing this at the top of my python file:
import sys
sys.path.append('''C:\code\my-library''')
from my-library import my-library
Then, my-library will be part of sys.path for as long as the session is active. If I start a new file, I have to remember to include sys.path.append again.
I feel like there must be a much better way of doing this. How can I make my-library available to every python script on my windows machine without having to use sys.path.append each time?
Simply add this path to your PYTHONPATH environment variable. To do this, go to Control Panel / System / Advanced / Environment variable, and in the "User variables" sections, check if you already have PYTHONPATH. If yes, select it and click "Edit", if not, click "New" to add it.
Paths in PYTHONPATH should be separated with ";".
You should use
os.path.join
to make your code more reliable.
You have already used __my-library__ in the path. So don't use it the second time in import.
If you have a directory structure like this
C:\code\my-library\lib.py and a function in there, e.g.:
def main():
print("Hello, world")
then your resulting code should be
import sys
sys.path.append(os.path.join('C:/', 'code', 'my-library'))
from lib import main
If this is a library that you use throughout your code, you should install it as such. Package it up properly, and either install it in your site-packages directory - or, if it's specific to certain projects, use virtualenv and install it just within the relevant virtualenvs.
To do such a thing, you'll have to use a sitecustomize.py (or usercustomize.py) file where you'll do your sys.path modifications (source python docs).
Create the sitecustomize.py file into the \Lib\site-packages directory of your python installation, and it will be imported each time a python interpreter is launched.
If you are doing this interactively, the best thing to do would be to install ipython and configure your startup settings to include that code. If you intend to have it be part of a script you run from the interpreter, the same thing applies, since it will have access to your namespace.
On the other hand, a stand alone script should not include that automatically. In the future, you or some other maintainer will come along, and all the code should be obvious, and not dependent upon a specific machine setup. The best thing to do would be to set up a skeleton file for new projects that includes all of the basic functionality you need. That, along with oft-used snippets will handle the problem.
All of your code to run the script, will be in the script, and you won't have to think about adding that code every time.
Using jupyter with multiple environments, adding the path to .bashrc didn't work. I had to edit the kernel.json file for that particular kernel and append it to the PYTHONPATH in env section.
This only worked in that kernel but maybe this can help someone else.

Get the directory of a Shortcut calling a Python Script

How does one acquire the directory of the Windows Shortcut calling a python script. I'd like to have multiple shortcuts in various places pointing to one script that I could edit if I wanted, but where the directory from which the script is called is accessible. Is this possible?
This script would likely then be compiled with py2exe or something, so if it is something that isn't possibly until THAT stage, I could go with that. Thanks!
The easiest solution is to just use a batch script instead of a shortcut.
All it needs is python C:\path\to\script\script.py, and the script will have the correct CWD.
The default when creating a shortcut on windows is for the Start in: property to be set to the folder the linked file resides in.
The script has no knowledge of the fact that it was called from a shortcut, let alone where that shortcut resides.
You can change the Start in: property of the shortcut to the path of the folder the shortcut resides in.
Then you can use os.getcwd() to get that path.
Unfortunately setting Start in: to . doesn't work.
In general you cannot obtain this information. You should use argv to switch behaviour of your script.
you can do so with
import os
print os.getcwd()
os.getcwd()
Return a string representing the current working directory.
Availability: Unix, Windows.

Categories