Get subset of path with specified folder - python

Suppose i have a path:
'C:\\Folder1\\Folder2\\Folder3\\Folder4'
Question is How Can i get subset of this path up to specified folder plus one directory down from specified folder.
Of course this should be generic, so folder names could be different.
For example with path from above, I specify such directory:
'Folder2'
And i want to get this path as a result:
'C:\\Folder1\\Folder2\\Folder3'

the os library has lots of features to manage paths. then a recursive method could allow to find the correct folder. try something like this:
import os
def find_folder( path, folder_name):
head, tail = os.path.split(path)
if folder_name == os.path.split(head)[1]:
return path
else:
return find_folder(head, folder_name)
path = 'C:\\Folder1\\Folder2\\Folder3\\Folder4'
print find_folder(path, 'Folder2')

hi you can try to split the path for example
import os
a=r"'C:\\Folder1\\Folder2\\Folder3\\Folder4'"
a.split(os.pathsep)
result is :
['C:', 'Folder1', 'Folder2', 'Folder3', 'Folder4']
remove the one you want
and concatenate after that the path .
Thanks and good luck !

Related

How to get path to file while the name of file is not full in python

I'll try to describe the problem in a simple way.
I have a .txt file that I can not know the full name of it which located under constant path
[for example: the full name is: Hello_stack.txt, I only can give to function the part: 'Hello_']
the input is: Path_to_file/ + 'Hello_'
the expected output is: Path_to_file/Hello_stack.txt
How can i do that?
I tried to give a path and check recursively if part of my file name is exist and if so, to return it's path.
this is my implementation: [of course I'd like to get another way if it works]
def get_CS_R2M_METRO_CALLBACK_FILE_PATH():
directory = 'path_of_file'
file_name = directory + 'part_of_file_name'
const_path = Path(file_name)
for path in [p for p in const_path.rglob("*")]:
if path.is_file():
return path
Thanks for help.
You might retrieve the file list in your path and then select from the list based upon your partial file name. Here is a snippet of code to perform that type of function on a Linux machine.
import os
dir = '/home/craig/Python_Programs/GetFile'
files = os.listdir(dir)
print('Files--> ', files)
for i in files:
myfile = 'Hello_'
if (myfile[0:4] == i[0:4]):
print('File(s) like \"Hello_\"-->', i)
When I executed this simple program over a directory/folder that had various files in the directory, here was the output to the terminal.
Una:~/Python_Programs/GetFile$ python3 GetFile.py
Files--> ['Hello_Stack.txt', 'Okay.txt', 'Hi_Stack.txt', 'GetFile.py', 'Hello_Stack.bak']
File(s) like "Hello_"--> Hello_Stack.txt
File(s) like "Hello_"--> Hello_Stack.bak
The literal value for your path would be different on a Windows machine. I hope this might provide you with a method to achieve your goal.
Regards.

Access folder with os

I want to iterate over a folder using a for-loop and os.listdir(), I'm just wondering what exactly to write into the brackets to access a particular file. Thanks!
The following example should help you:
import os
path = "C:/Users/TestDir"
dirs = os.listdir( path )
for file in dirs:
print(file)
You could easily google that. https://www.tutorialspoint.com/python/os_listdir.htm
You only need the path in the brackets.
According to what i understood, you would like to iterate over files inside a particular folder until you find one particular file? You could do something like:
import os
FileToBeFound = "Your File Name To Find"
path = "Path to the directory you would like to check for a file in"
for file in os.listdir(path):
if file == FileToBeFound:
#do stuff with file
break
else:
continue

Python get all the file name in a list

The problem is to get all the file names in a list that are under a particular directory and in a particular condition.
We have a directory named "test_dir".
There, we have sub directory "sub_dir_1", "sub_dir_2", "sub_dir_3"
and inside of each sub dir, we have some files.
sub_dir_1 has files ['test.txt', 'test.wav']
sub_dir_2 has files ['test_2.txt', 'test.wav']
sub_dir_2 has files ['test_3.txt', 'test_3.tsv']
What I want to get at the end of the day is a list of of the "test.wav" that exist under the "directory" ['sub_dir_1/test.wav', 'sub_dir_2/test.wav']. As you can see the condition is to get every path of 'test.wav' under the mother directory.
mother_dir_name = "directory"
get_test_wav(mother_dir_name)
returns --> ['sub_dir_1/test.wav', 'sub_dir_2/test.wav']
EDITED
I have changed the direction of the problem.
We first have this list of file names
["sub_dir_1/test.wav","sub_dir_2/test.wav","abc.csv","abc.json","sub_dir_3/test.json"]
from this list I would like to get a list that does not contain any path that contains "test.wav" like below
["abc.csv","abc.json","sub_dir_3/test.json"]
You can use glob patterns for this. Using pathlib,
from pathlib import Path
mother_dir = Path("directory")
list(mother_dir.glob("sub_dir_*/*.wav"))
Notice that I was fairly specific about which subdirectories to check - anything starting with "sub_dir_". You can change that pattern as needed to fit your environment.
Use os.walk():
import os
def get_test_wav(folder):
found = []
for root, folders, files in os.walk(folder):
for file in files:
if file == "test.wav":
found.append(os.path.join(root, file))
return found
Or a list comprehension approach:
import os
def get_test_wav(folder):
found = [f"{arr[0]}\\test.wav" for arr in os.walk(folder) if "test.wav" in arr[2]]
return found
I think this might help you How can I search sub-folders using glob.glob module?
The main way to make a list of files in a folder (to make it callable later) is:
file_path = os.path.join(motherdirectopry, 'subdirectory')
list_files = glob.glob(file_path + "/*.wav")
just check that link to see how you can join all sub-directories in a folder.
This will also give you all the file in sub directories that only has .wav at the end:
os.chdir(motherdirectory)
glob.glob('**/*.wav', recursive=True)

Renaming multiple sub folders to match the parent folder's name

I'm a python beginner but have some basic experience, and I need someone to please help me use the os module to rename sub folders based on their parent folder. I've been searching for answers for the past week and have not had any success. I'm assuming I need to use the os.walk method to do this.
Here is my folder structure:
C:\data\test\
C:\data\test\map1
C:\data\test\map1\1617151
C:\data\test\map2
C:\data\test\map2\181719
C:\data\test\map3
C:\data\test\map3\182726
C:\data\test\map4
C:\data\test\map4\894932
I need the results to look like this.
C:\data\test\
C:\data\test\map1
C:\data\test\map1\map1
C:\data\test\map2
C:\data\test\map2\map2
C:\data\test\map3
C:\data\test\map3\map3
C:\data\test\map4
C:\data\test\map4\map4
Can someone please help?
python 2.7:
import os
os.chdir("C:\data\test\") # go to dir
sub_dirs = os.walk('.').next()[1] # get list of subdirs
for sub_dir in sub_dirs:
sub_sub_dir = os.walk('.').next[1] # get sub-subdir
os.rmdir(sub_sub_dir) # remove sub-subdir
os.makedirs(sub_dir + '\bla') # make new sub-subdir named subdir\bla
python 3+:
import os
os.chdir("C:\data\test\")
sub_dirs=next(os.walk('.'))[1]
for sub_dir in sub_dirs:
sub_sub_dir = next(os.walk('.'))[1]
os.rmdir(sub_sub_dir)
os.makedirs(sub_dir + '\bla')
Untested, but should do it.
You can get a list of all the files and it's respective folder location using this one liner:
here = '.' # Current location
files = [(root, files) for root, dirs, files in os.walk(here) if (not dirs and files)]
For the given folder structure it will return:
[
('C:\data\test\map1', ['1617151']),
...
]
You can now loop over this list and rename the files (https://docs.python.org/3/library/os.html#os.rename). You can get the parent folder's name by splitting the root string (root.split('\')[-1]).

Create path and filename from string in Python

Given the following strings:
dir/dir2/dir3/dir3/file.txt
dir/dir2/dir3/file.txt
example/directory/path/file.txt
I am looking to create the correct directories and blank files within those directories.
I imported the os module and I saw that there is a mkdir function, but I am not sure what to do to create the whole path and blank files. Any help would be appreciated. Thank you.
Here is the answer on all your questions (directory creation and blank file creation)
import os
fileList = ["dir/dir2/dir3/dir3/file.txt",
"dir/dir2/dir3/file.txt",
"example/directory/path/file.txt"]
for file in fileList:
dir = os.path.dirname(file)
# create directory if it does not exist
if not os.path.exists(dir):
os.makedirs(dir)
# Create blank file if it does not exist
with open(file, "w"):
pass
First of all, given that try to create directory under a directory that doesn't exist, os.mkdir will raise an error. As such, you need to walk through the paths and check whether each of the subdirectories has or has not been created (and use mkdir as required). Alternative, you can use os.makedirs to handle this iteration for you.
A full path can be split into directory name and filename with os.path.split.
Example:
import os
(dirname, filename) = os.path.split('dir/dir2/dir3/dir3/file.txt')
os.makedirs(dirname)
Given we have a set of dirs we want to create, simply use a for loop to iterate through them. Schematically:
dirlist = ['dir1...', 'dir2...', 'dir3...']
for dir in dirlist:
os.makedirs( ... )

Categories