Get windows/system folder location in Python - python

How would I go about getting the Windows/System folder paths in python? I need to be able to read from an INI that gets written to the Windows directory.

Use the environment variable %WINDIR%.
import os
winpath = os.environ['WINDIR'] + "\\System\\"
inifile = open(winpath + filename)

Related

How to create a Path from a variable?

I have been running some script in VBA which I like to convert in Python. In VBA I use variables to identify the path from which the raw data are collected so that the same script can be used in any machine. In order to do do so in VBA I identify the path by using the using the following string:
"C:\Users\" & Environ$("username") & "\Data"
Is there a way I can identify in the same way the path in Python?
Use pathlib from the Python Standard Library.
import pathlib
print(pathlib.Path.home() / 'Data')
In older versions of Python (before pathlib) you could use os.path.
import os.path
print(os.path.join(os.path.expanduser('~'), 'Data'))
Some additional info: if you want to reference the path where your script is, you can do that too. You just have to know that __file__ contains the full path to your script.
import pathlib
# full path to the script
print(pathlib.Path(__file__))
# full path to the scripts folder
print(pathlib.Path(__file__).parent)
# full path to the subfolder 'subfolder' in the scripts folder
print(pathlib.Path(__file__).parent / 'subfolder')
# full path to a file in the subfolder
print(pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv')
Just to add to Matthias answer: in case you are looking to use python to "find" a path to the save a file you should keep in mind that despite printing the correct path, Python won't recognize the path unless, after identify the correct Path, you convert it to a string
i.e.: suppose you set your path as a variable
path = pathlib.Path(__file__).parent / 'subfolder' / 'datafile.csv'
then you need to covert path as a string to be used to open/save a file
path1 = str(path)
then you can use path1 to open/save a file

Accessing text files out of python directory

I am doing a project using python in which I got stuck at a point where I want to access some text files which are saved outside the project directory.
The path where my text files are saved:
C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w
The path of my python project:
C:\Users\saqibshakeel035\PycharmProjects\Tutorial_1
I want to open/read my text files (external > not included in python project folder)
I already know the Reading/writing etc etc within the same folder where the python project .py file is present but struggling with the different paths.
I tried:
import os
from os import path
print("Your cunrrent directory is : %s" %path.curdir)
strpath = r"C:\Users\saqibshakeel035\Desktop\Scientific Project Lithim battery project\text_file_r_w"
print("Your current directory is %s: " %path.dirname(strpath))
print("Your current directory is : %s" %path.abspath(strpath))
This works fine and it shows my abspath where my text files are stored but when I try to read it with the following command
f = open("file1.txt","r")
It gives error that no such directory or file found
I suggest you try f = open("C:/text/to/path/file1.txt","r") or the code #Jaba has mention. Either works fine
Can you try using the full path to "file1.txt" in the open function.
f = open("Full_path_to_file1.txt", "r")
Another option is to change the current directory,
os.chdir(path)

How to load dependencies and subfolders in Pycharm?

I am so new with python and pycharm and i got confuse!!
When I run my project in pycharm it gives me an error about not finding the path of my file. The physical file path is:
'../Project/BC/RequiredFiles/resources/a_reqs.csv'
My project working directory is "Project/BC" and the project running file (startApp.sh) is there too. but the .py file that wants to work with a_req.csv is inside the "RequiredFiles" folder. There is the following code in the .py file:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
it returns: '../Project/BC/resources/a_reqs.csv'
instead of: '../Project/BC/resources/RequiredFiles/a_reqs.csv'
while the .py file is in "RequiredFiles" the os.getcwd() must include it too. but it does not.
The problem is that i can not change the addressing code. because this code works in another IDE and other people who work with the code in other platform or OS do not have any problem. I am working in mac OS and if i am not mistaken the code works with windows!!
So, how can i tell Pycharm (in mac) to see and load "RequiredFiles" folder as the subfolder of my working directory!!!
os.getcwd returns the current working directory of the process (which may be the directory where startApp.sh is located or another one, depending on the PyCharm's run configuration setting, or, if you start the program from the command line, the directory in which you execute the command).
To make a path independent on the current working directory, you can take the directory where your Python file is located and build the path from it:
os.path.dirname(__file__) + "/resources/a_reqs.csv"
From your question what I see is:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
Which produces: "../Project/BC/resources/a_reqs.csv", whereas your desired output is
"../Project/BC/resources/RequiredFiles/a_reqs.csv". Since we know os.getcwd is returning "/Project/BC/", then to get your desired result you should be doing:
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
But since you want the solution to work with or without the RequiredFiles subdirectory you could apply a conditional solution, ie something like:
import os.path
if os.path.exists(os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"):
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
else:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
This solution will set the reqsfile to the csv in the RequiredFiles directory if the directory exists, and thus will work for you. On the other-hand, if the RequiredFiles directory doesn't exist, it will default to the csv in /resources/.
Typically when groups collaborate on projects, the maintain the same file hierarchy so that these types of issues are avoided, so you might want to consider moving the csv from /RequiredFiles/ to /resources/.

How to set current working directory in python in a automatic way

How can I set the current path of my python file "myproject.py" to the file itself?
I do not want something like this:
path = "the path of myproject.py"
In mathematica I can set:
SetDirectory[NotebookDirectory[]]
The advantage with the code in Mathematica is that if I change the path of my Mathematica file, for example if I give it to someone else or I put it in another folder, I do not need to do anything extra. Each time Mathematica automatically set the directory to the current folder.
I want something similar to this in Python.
The right solution is not to change the current working directory, but to get the full path to the directory containing your script or module then use os.path.join to build your files path:
import os
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
# then:
myfile_path = os.path.join(ROOT_PATH, "myfile.txt")
This is safer than messing with current working directory (hint : what would happen if another module changes the current working directory after you did but before you access your files ?)
I want to set the directory in which the python file is, as working directory
There are two step:
Find out path to the python file
Set its parent directory as the working directory
The 2nd is simple:
import os
os.chdir(module_dir) # set working directory
The 1st might be complex if you want to support a general case (python file that is run as a script directly, python file that is imported in another module, python file that is symlinked, etc). Here's one possible solution:
import inspect
import os
module_path = inspect.getfile(inspect.currentframe())
module_dir = os.path.realpath(os.path.dirname(module_path))
Use the os.getcwd() function from the built in os module also there's os.getcwdu() which returns a unicode object of the current working directory
Example usage:
import os
path = os.getcwd()
print path
#C:\Users\KDawG\Desktop\Python

How can I have Python look for files in the location of the program?

I'm having a problem with a program in which I have to load images and pickled objects: my Python software doesn't appear to be looking in the location of the program. I have my program in a folder called "King's Capture," and my images in a folder within "King's Capture" labeled "data." I want to have python find the files no matter where I place the folder "King's Capture." It seems to me that python should already be looking in the folder where the program itself is, but it apparently isn't. How should I go about this?
You can access the path of the current script file via the special variable __file__. So try this within your main program script:
import os
// ...
data_dir = os.path.join(os.path.dirname(__file__), 'data')
Try this
import sys, os
ROOT = os.path.dirname(os.path.abspath(__file__))
directory = ROOT + os.path.sep + 'data'
for eachFile in os.listdir(directory):
fileName = directory + os.path.sep + eachFile
print fileName

Categories