How to get the name of parent directory in Python? [duplicate] - python

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))

Related

How to normalize a relative path using pathlib

I'm trying to use relative paths in Python, and I want to put my csv files in a separate folder from my python code.
My python program is in the following folder:
G:\projects\code
I want to read this file which is one level up:
G:\projects\data\sales.csv
How do I specify a path using pathlib that is one level up from my current working folder? I don't want to change the current working folder.
I tried this:
from pathlib import Path
file = Path.cwd() /'..'/'data'/'sales.csv'
But now the 'file' variable equals this:
'G:/projects/code/../data/sales.csv'
I read through the docs and either it isn't explained there or I'm just missing it.
Although it's not a problem that your path includes '..' (you can still use this path to open files, etc. in Python), you can normalize the path using resolve():
from pathlib import Path
path = Path.cwd() / '..' / 'data' / 'sales.csv'
print(path) # WindowsPath('G:/projects/code/../data/sales.csv')
print(path.resolve()) # WindowsPath('G:/projects/data/sales.csv')
NB: I personally would name a variable that contains a path path, not file. So you could later on do file = open(path).
print(
Path(__file__).parent, # the folder
Path(__file__).parent.parent, # the folder's parent
sep='\n'
)
print(
Path(
Path(__file__).parent.parent, 'hello.py'
)
)
results in
C:\Users\isik\Desktop\Python\MessAround\project\module
C:\Users\isik\Desktop\Python\MessAround\project
C:\Users\isik\Desktop\Python\MessAround\project\hello.py
with this file structure
-project
-module
-__init__.py
-hello.py
-__init__.py
while the code is located inside project.module.__init__.py
Do you mean "read my csv files"?
The import keyword has a different meaning in Python (you import only other Python modules).
In any case, in order to read a file located one folder above your Python file, you can use this:
import os
filePath = os.path.dirname(__file__)+'/../'+fileName
fileDesc = open(filePath)
fileData = fileDesc.read()
fileDesc.close()
...
here is an example I used:
import json
from pathlib import Path
def read_files(folder_name, file_name):
base_path = Path.cwd().joinpath('configs','resources')
path = base_path.joinpath(folder_name,file_name)
open_file = open(path,'r')
return json.load(open_file.read())
This is pretty old, but I happened on it looking for something else.
Oddly you never got a direct, obvious, answer -- you want the parent property:
from pathlib import Path
file = Path.cwd().parent / 'data' / 'sales.csv'
Note that some of the answers that say you want __file__ rather than the current working directory may be correct (depending on your use case), in which case it's:
from pathlib import Path
file = Path(__file__).parent.parent / 'data' / 'sales.csv'
(parent of the python file is the code dir, parent of that is the projects dir.
However, It's not great practice to refer to your data by its relative path to your code -- I think using the cwd is a better option -- though what you should do is pass the path to the data in to the script via sys.argv.

Is there a way to view the directory that a file is in using python? [duplicate]

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())

Python Constants for a file path [duplicate]

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.

How do I create a string containing the filepath of my python program?

We are creating a python program that executes specific macros within Polyworks based on user input into the program. Right now the code is:
roto.command.CommandExecute('MACRO EXEC("C:\\RotoWorks\\Macros\\CentrifugalCompressor")')
However this assumes that our program is always installed in C:\RotoWorks. Ideally, our app is portable. I'm sure theres a way to retrieve the filepath that Rotoworks is stored in, then just concatenate the rest of the filepath to the end. How do I do this?
You can retrieve the path from the __file__ attribute of the file. Use os.path.abspath on that attribute to retrieve the absolute path of the file and then os.path.dirname to retrieve the containing directory:
import os
file_directory = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(file_directory, other_path) # join directory to an inner path
roto.command.CommandExecute('MACRO EXEC({})'.format(path))
Use os.path.dirname recursively to move out as many directories as you want.

File not found error python [duplicate]

This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 4 years ago.
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
print(files + time.ctime(os.path.getatime(files)))
I am getting a file not found error when running this script.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'TORRENT NAME.torrent'
everything works fine until time.ctime(os.path.getatime(files)
is added into the mix.
I would like the script to display 'torrent name' 'date last modified'
for each file in the folder.
Why is the error referencing a file, by name that it says it is unable to find and how can i fix this?
Your files variable is the file name only, not the complete path. Hence it will be looking for it in your current working directory, not where listdir found it.
The following code will use the full path name:
import os
import time
folder = r'C:\users\chris\desktop\torrent'
files = os.listdir(folder)
for file in files:
if file.endswith(".torrent"):
print(file + " " + time.ctime(os.path.getatime(os.path.join(folder,file))))
The os.path.join() combines folder and file to give you a full path specification. For example, os.path.join("/temp","junk.txt") would give you /temp/junk.txt (under UNIX).
Then it uses that in exactly the same way you tried to use just the file variable, getting the last access time and formatting it in a readable manner.
It require absolute path.
os.path.getatime(path)
Return the time of last access of path.
so, open('xxx.torrent') will not work.
Instead, use open('C:\users\chris\desktop\torrents\xxx.torrent')
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
filepath = os.path.join('C:\users\chris\desktop\torrents',files)
print(files + time.ctime(os.path.getatime(filepath)))

Categories

Resources