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)
Related
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)
This question already has answers here:
Python Deleting Certain File Extensions
(2 answers)
Closed 4 years ago.
First off, let me apologize if the title is unclear.
To simplify a task I do at work, I've started writing this script to automate the removal of files from a certain path.
My issue is that in its current state, this script does not check the contents of the folders within the folder provided by the path.
I'm not sure how to fix this, because from what I can tell, it should be checking those files?
import os
def depdelete(path):
for f in os.listdir(path):
if f.endswith('.exe'):
os.remove(os.path.join(path, f))
print('Dep Files have been deleted.')
else:
print('No Dep Files Present.')
def DepInput():
print('Hello, Welcome to DepDelete!')
print('What is the path?')
path = input()
depdelete(path)
DepInput()
Try using os.walk to traverse the directory tree, like this:
def depdelete(path):
for root, _, file_list in os.walk(path):
print("In directory {}".format(root))
for file_name in file_list:
if file_name.endswith(".exe"):
os.remove(os.path.join(root, file_name))
print("Deleted {}".format(os.path.join(root, file_name)))
Here are the docs (there are some usage examples towards the bottom): https://docs.python.org/3/library/os.html#os.walk
Currently, your code just loops over all files and folders in the provided folder and checks each one for its name. In order to also check the contents of folders within path, you have to make your code recursive.
You can use os.walk to go through the directory tree in path and then check its contents.
You'll find a more detailed answer with code examples at Recursive sub folder search and return files in a list python.
Take a look at os.walk()
This function will iterate through sub-directories for you. The loop will look like this.
for subdir, dirs, files in os.walk(path):
for f in files:
if f.endswith('.exe'):
fullFile = os.path.join(subdir, f)
os.remove(fullFile)
print (fullFile + " was deleted")
You're looking for os.walk(). In your case, it could work like so:
import os
def dep_delete(path):
for path, dirs, files in os.walk(path):
for f in files:
if f.endswith('.exe'):
os.remove(os.path.join(path, f))
print('Dep files have been deleted.')
def dep_input():
print('Hello, Welcome to dep_delete!')
print('What is the path?')
path = input()
dep_delete(path)
dep_input()
Also see: List directory tree structure in python?
This question already has answers here:
Using os.walk() to recursively traverse directories in Python
(14 answers)
Closed 4 years ago.
I'm currently writing a python script which you can give a drive or folder, and it then iterates through every image on the drive or folder and moves them all into one folder.
My issue is that using os.walk, it isn't opening the subdirs automatically. As an example, say I chose the E: drive to scan. E: drives file structure;
E:
+ Folder1
- file.png
- file2.png
- files.jpg
The only file that my script will detect is files.jpg, as the other files are nested in a subdir, which os.walk does not open and check for files.
Here's the code I'm using as of right now;
# For each file in the drive
for folders, sub_folders, files in os.walk(drive):
# For each name in the files
for filename in files:
if filename == drive + "\\ImageSorter\\":
continue
file_name = os.path.splitext(filename)[0]
extension = os.path.splitext(filename)[1]
Is there a way to get os.walk to iterate through all subdirs on the drive, rather than just the first folder?
Try this code
import os
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)
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 #
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)