Every time I want to open a text file that's on Desktop, I always need to change the directory in Python with these commands:
>>> import os
>>> os.chdir("C:/Users/Name/Desktop")
It's really annoying when I have to change it every time.
It's currently in C:\\Python34
.
So how do I permanently set the working directory to Desktop?
Thanks in advance!
To change the current working directory (CWD) os.chdir () method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path. Note: The current working directory is the folder in which the Python script is operating.
If you want to find the directory where the script is located, use os.path.realpath (__file__). It will return a string containing the absolute path to the running script. Changing the Current Working Directory in Python To change the current working directory in Python, use the chdir () method.
The os.path.dirname () method in python is used to get the directory name from the path. import os path = os.getcwd () print ("Current directory", path) print () parent = os.path.dirname (path) print ("Parent directory", parent) After writing the above code (python get parent of current directory), Ones you will print “parent” then ...
Now, let’s take a look at changing working directories using relative paths in Python. To move up a folder with a relative path you can simply use ../, while moving down in the current directory involves simply adding that directory name into the script.
You can add the line to your PYTHONSTARTUP file. So when you start an interpreter os.chdir("C:/Users/Name/Desktop")
will be run.
I have a startup.py
in my home directory file with the following content:
print("(.startup.py)")
import datetime, os, pprint, re, sys, time
print("(imported datetime, os, pprint, re, sys, time)")
So every time I start ipython or a python shell those lines are executed.
Not 100 percent but I imagine setting the PYTHONSTARTUP="path_to_script"
in your environment variables on windows should do the trick with the two lines in your question in the startup file.
So for your situation you can create a file lets call it startup.py and inside that file you put:
import os
os.chdir("C:/Users/Name/Desktop")
Then the steps to add environment variable PYTHONSTARTUP:
For windows 8:
From the Desktop, right-click the very bottom left corner of the screen to get the Power User Task Menu.
From the Power User Task Menu, click System. Click the Advanced System Settings link in the left column.
Under System variables, click New.
Add PYTHONSTARTUP to Variable name.
Add the path of the Python file to Variable value and click OK. # <-path_to_startup.py
Click OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With