This question already has answers here:
How do I get the full path of the current file's directory?
(12 answers)
Closed 6 years ago.
I need a constant for a file(database) path, as a base_directory. I know there are no real constants in python.
I set this way:
base_dir = (os.getcwd().rsplit('\\', 2)[0],)
I need this value in multiple files, in different directories/folders levels/depths. So I created a file with variables and I import the file where is needed.
The problem is that the base_dir is not calculated based were is the location(path) of the imported file, but based on the location of the current file.
So I have different paths based on the path depth.
I can change every time the base_dir to adapt to the new path, but I need to repeat not only the var declaration but a lot of related code for every file.
How can this be fixed, simulating a constant for a path?
No need to use os.getcwd. Get your constants file path with os.path.abspath:
file_abs_path = os.path.abspath(os.path.dirname(__file__))
And build path to database file with os.path.join:
database_path = os.path.join(file_abs_path, '..', 'path', 'to', 'db)
Then import constants and access constants.database_path.
Related
This question already has answers here:
python - Finding the user's "Downloads" folder
(6 answers)
Closed 2 months ago.
I am wanting to set up a system of CSV formatters in conjunction with a PySimpleGUI program. I want the output file to go to the users Downloads folder, but currently I know how to only use the Path method for my own Downloads folder. If I packaged this up, it would not be dynamic.
path = Path(r"C:\\Users\\xxx.xxxxx\\downloads\\Finished_File.csv")
I am unsure of other ways to go about auto-filling the user info without inputting it manually
My only other thinking is perhaps have this change dynamically with PySimpleGui using a list of potential names, and then having the user set who they are?
Find it manually before saving uisng pathlib
from pathlib import Path
users_download_path = str(Path.home() / "Downloads")
res =str( users_download_path) + '\' + str('Finished_File.csv')
path = Path(res)
This question already has answers here:
Find the current directory and file's directory [duplicate]
(13 answers)
Closed 3 years ago.
For a project I am working on in python, I need to be able to view what directory a file is in. Essentially it is a find function, however I have no idea how to do this using python.
I have tried searching on google, but only found how to view files inside a directory. I want to view directory using a file name.
To summarise: I don't know the directory, and want to find it using the file inside it.
Thanks.
In Python, the common standard libraries for working with your local files are:
os.path
os
pathlib
If you have a path to a file & want it's directory, then we need to extract it:
>>> import os
>>> filepath = '/Users/guest/Desktop/blogpost.md'
>>> os.path.dirname(filepath) # Returns a string of the directory name
'/Users/guest/Desktop'
If you want the directory of your script, the keyword you need to search for is the "current working directory":
>>> import os
>>> os.getcwd() # returns a string of the current working directory
'/Users/guest/Desktop'
Also check out this SO post for more common operations you'll likely need.
Here's what I did:
import os
print(os.getcwd())
This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 6 months ago.
I have a file 7.csv in directory: '~/Documents/Jane/analyst/test/1/'. I was able to read this file using pandas.read_csv function with no problem.
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
pd.read_csv(f_path, index_col=None, header=0)
But when checking whether this file is exsiting using os.path.isfile(), the result return False.
os.path.isfile(f_path)
False
What could be the the possible error source?
Both os.path.isfile() and os.path.exists() do not recognize ~ as the home directory. ~ is a shell variable not recognized in python. It has to be either fully specified or you can use relative directory name.
But if you want to use ~ as home, you can do
from os.path import expanduser
home = expanduser("~")
As hun mentioned, your code should be
import os
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
os.path.isfile(os.path.expanduser(f_path))
This will expand the tilde into an absolute path. ~, . and .. do not have the same meaning to the python os package that they do in a unix shell and need to be interpreted by separate functions.
This question already has answers here:
How do I get the parent directory in Python?
(21 answers)
Closed 7 years ago.
I have a program in python that prints out information about the file system... I need to know to save the name of the parent directory to a variable...
For example, if a tiny bit of the file system looked like this:
ParentDirectory
ChildDirectory
SubDirectory
If I was inside of ChildDirectory, I would need to save the name ParentDirectory to a certain string... here is some pseudo code:
import os
var = os.path.parent()
print var
On a side note, I am using Python 2.7.6, so I need to be compatible with 2.7.6...
You can get the complete file path for the script resides using __file__ variable , then you can use os.path.abspath() to get the absolute path of your file , and then use os.path.join() along with your current path , and the parent directory descriptor - .. in most operating systems , but you can use os.pardir (to get that from python , so that it is truly platform independent) and then again get its absolute path to get the complete path of current directory, then use it with same logic again to get its parent directory.
Example code -
import os,os.path
curfilePath = os.path.abspath(__file__)
# this will return current directory in which python file resides.
curDir = os.path.abspath(os.path.join(curfilePath, os.pardir))
# this will return parent directory.
parentDir = os.path.abspath(os.path.join(curDir, os.pardir))
This question already has answers here:
Is there a built in function for string natural sort?
(23 answers)
Closed 9 years ago.
I have a number of files in a folder with names following the convention:
0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...
I need to read them one by one and manipulate the data inside them. Currently I open each file with the command:
import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
...
Unfortunately this reads the files in no particular order (not sure how it picks them) and I need to read them starting with the one having the minimum number as a filename, then the one with the immediate larger number and so on until the last one.
A simple example using sorted() that returns a new sorted list.
import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
print data_file
You can read more here at the Docs
Edit for natural sorting:
If you are looking for natural sorting you can see this great post by #unutbu