Avoid including the current and parent directories [duplicate] - python

This question already has answers here:
Excluding directories in os.walk
(2 answers)
Closed 5 years ago.
So, I'm looping through my files and folders as follows:
for root, dirs, files in os.walk(img):
How can we avoid including the current (.) and parent (..) directories in such search?
Thanks.

os.walk() wouldn't plow through your parent directory (I'm assuming you mean the parent of img), so you wouldn't need to worry there. If you just want to skip the current directory assigned to img, it's simple:
for root, dirs, files in os.walk(img):
if root == img: continue
# your code for the children dirs and files here #

Related

How to move and enter folders and subfolders in python [duplicate]

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 2 years ago.
i have a dataset and one folder and in this folder i have a few subfolder in them there is audio file i need to move on the whole subfolders and get the file and the path , i using python
osomeone has idea?
folder: dataset -> folders: rock,regge,hiphop,classic,disco,jazz,pop,blues,country,metal -> files: "name".wav
i need to enter each folder and get the file and path.
i have 100 files in folder.
i dont try nothing because i dont know how to do that
You should use os.walk
import os
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir + os.sep + file
if filepath.endswith(".wav"):
print(filepath)

Rename part of the name in any files or directories in Python [duplicate]

This question already has answers here:
How to rename a file using Python
(17 answers)
Closed 3 years ago.
I have a root folder with several folders and files and I need to use Python to rename all matching correspondences. For example, I want to rename files and folders that contain the word "test" and replace with "earth"
I'm using Ubuntu Server 18.04. I already tried some codes. But I'll leave the last one I tried. I think this is really easy to do but I don't have almost any knowledge in py and this is the only solution I have currently.
import os
def replace(fpath, test, earth):
for path, subdirs, files in os.walk(fpath):
for name in files:
if(test.lower() in name.lower()):
os.rename(os.path.join(path,name), os.path.join(path,
name.lower().replace(test,earth)))
Is expected to go through all files and folders and change the name from test to earth
Here's some working code for you:
def replace(fpath):
filenames = os.listdir()
os.chdir(fpath)
for file in filenames:
if '.' not in file:
replace(file)
os.rename(file, file.replace('test', 'earth'))
Here's an explanation of the code:
First we get a list of the filenames in the directory
After that we switch to the desired folder
Then we iterate through the filenames
The program will try to replace any instances of 'test' in each filename with 'earth'
Then it will rename the files with 'test' in the name to the version with 'test' replaced
If the file it is currently iterating over is a folder, it runs the function again with the new folder, but after that is done it will revert back to the original
Edited to add recursive iteration through subfolders.

Recursively enter each subdirectory of a directory in Python [duplicate]

This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 4 years ago.
I am new to Python and I am trying to write a function that will be able to enter inside a folder if there all files it should just print their names if it is a folder it should go inside it and print it's files, if there is a folder inside this folder it should also go inside and do that until there is nothing left. For now I haven't found a way to go that deep. Is there a way to do that recursively? How should I proceed my code for some reason doesn't enter all subdirectories. Thanks in advance
def list_files(startpath, d):
for root, dirs, files in os.walk(startpath):
for f in files:
print (f)
for di in dirs:
print (di)
list_files(di, d + 1)
list_files(path, 0)
May be you can check this answer:
Using os.walk() to recursively traverse directories in Python
which employs os.walk() method like this.
import os
# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
for file in files:
print(len(path) * '---', file)

How to iterate over folders in Python [duplicate]

This question already has answers here:
How can I iterate over files in a given directory?
(11 answers)
Closed 5 months ago.
Have repository folder in which I have 100 folders of images. I want to iterate over each folder and then do the same over images inside these folders.
for example : repository --> folder1 --> folder1_images ,folder2 --> folder2_images ,folder3 --> folder3_images
May someone know elegante way of doing it?
P.S my OS is MacOS (have .DS_Store files of metadata inside)
You can do use os.walk to visit every subdirectory, recursively. Here's a general starting point:
import os
parent_dir = '/home/example/folder/'
for subdir, dirs, files in os.walk(parent_dir):
for file in files:
print os.path.join(subdir, file)
Instead of print, you can do whatever you want, such as checking that the file type is image or not, as required here.
Have a look at os.walk which is meant exactly to loop through sub-directories and the files in them.
More info at : https://www.tutorialspoint.com/python/os_walk.htm
Everyone has covered how to iterate through directories recursively, but if you don't need to go through all directories recursively, and you just want to iterate over the subdirectories in the current folder, you could do something like this:
dirs = list(filter(lambda d: os.path.isdir(d), os.listdir(".")))
Annoyingly, the listdir function doesn't only list directories, it also lists files as well, so you have to apply the os.path.isdir() function to conditionally 'extract' the elements from the list only if they're a directory and not a file.
(Tested with Python 3.10.6)

How to get list of subdirectories names [duplicate]

This question already has answers here:
How to get all of the immediate subdirectories in Python
(15 answers)
Closed 7 years ago.
There is a directory that contains folders as well as files of different formats.
import os
my_list = os.listdir('My_directory')
will return full content of files and folders names. I can use, for example, endswith('.txt') method to select just text files names, but how to get list of just folders names?
I usually check for directories, while assembling a list in one go. Assuming that there is a directory called foo, that I would like to check for sub-directories:
import os
output = [dI for dI in os.listdir('foo') if os.path.isdir(os.path.join('foo',dI))]
You can use os.walk() in various ways
(1) to get the relative paths of subdirectories. Note that '.' is the same value you get from os.getcwd()
for i,j,y in os.walk('.'):
print(i)
(2) to get the full paths of subdirectories
for root, dirs, files in os.walk('path'):
print(root)
(3) to get a list of subdirectories folder names
dir_list = []
for root, dirs, files in os.walk(path):
dir_list.extend(dirs)
print(dir_list)
(4) Another way is glob module (see this answer)
Just use os.path.isdir on the results returned by os.listdir, as in:
def listdirs(path):
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
That should work :
my_dirs = [d for d in os.listdir('My_directory') if os.path.isdir(os.path.join('My_directory', d))]
os.walk already splits files and folders up into different lists, and works recursively:
for root,dirs,_ in os.walk('.'):
for d in dirs:
print os.path.join(root,d)

Categories

Resources