how in python remove all folder inside path - python

How can I list all folders of a directory in Python and remove them ?
for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(root)
print(dirs)
print(files)
i run this code in Centos7 but i just need list folder for delete times

import os
import shutil
dirs= next(os.walk(r'/home/m110/public_html/ts/'))[1]
for name in dirs:
print name
shutil.rmtree(name)

Related

loop through folders and copy similar folders

with python how can i loop through folders and copy out subfolders with the same name from every folder and save it in a unique folder with the name. so A in test 1 and in test 2 should be copied to a folder called A and loop through doing the same for the rest
i was able to loop through the main dir and got the dir(test 1 and test#) by using os.walk command
Are you looking for something like this?
import os, shutil;
directory = "/home/.../test1";
dest_dir = "/home/.../test2";
filelist = [];
for root, dirs, files in os.walk(directory):
for file in files:
filelist.append(os.path.join(root,file));
for subFile in filelist:
shutil.copy(subFile, dest_dir);

Extract all files from multiple folders with Python

I wrote down this code:
import shutil
files = os.listdir(path, path=None)
for d in os.listdir(path):
for f in files:
shutil.move(d+f, path)
I want every folder in a given directory (path) with files inside, the files contained in that folder are moved to the main directory(path) where the folder is contained.
For Example:
The files in this folder: C:/example/subfolder/
Will be moved in: C:/example/
(And the directory will be deleted.)
Sorry for my bad english :)
This should be what you are looking for, first we get all subfolders in our main folder. Then for each subfolder we get files contained inside and create our source path and destination path for shutil.move.
import os
import shutil
folder = r"<MAIN FOLDER>"
subfolders = [f.path for f in os.scandir(folder) if f.is_dir()]
for sub in subfolders:
for f in os.listdir(sub):
src = os.path.join(sub, f)
dst = os.path.join(folder, f)
shutil.move(src, dst)
Here another example , using a few lines with glob
import os
import shutil
import glob
inputs=glob.glob('D:\\my\\folder_with_sub\\*')
outputs='D:\\my\\folder_dest\\'
for f in inputs:
shutil.move(f, outputs)

Check if path is empty in glob?

Check if any folder in the glob search is empty and print their names.
There are some folders that are empty in the directories.
This is the code:
for i in glob.iglob('**/Desktop/testna/**' ,recursive = True):
if not os.listdir(i):
print(f'{i} is empty' + '\n')
Returns:
NotADirectoryError
Finding empty directories is a lot easier with os.walk:
import os
print([root for root, dirs, files in os.walk('/') if not files and not dirs])
Or if you prefer to print the files line by line:
import os
for root, dirs, files in os.walk('/'):
if not files and not dirs:
print(root)

Python: Remove empty folders recursively

I'm having troubles finding and deleting empty folders with my Python script.
I have some directories with files more or less like this:
A/
--B/
----a.txt
----b.pdf
--C/
----d.pdf
I'm trying to delete all files which aren't PDFs and after that delete all empty folders. I can delete the files that I want to, but then I can't get the empty directories. What I'm doing wrong?
os.chdir(path+"/"+name+"/Test Data/Checklists")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists"):
for name in files:
if not(name.endswith(".pdf")):
os.remove(os.path.join(root, name))
pprint("Deletting empty folders..")
pprint("Current path: "+ os.getcwd())
for root, dirs, files in os.walk(path+"/"+name+"/Test Data/Checklists", topdown=False):
if not dirs and not files:
os.rmdir(root)
use insted the function
os.removedirs(path)
this will remove directories until the parent directory is not empty.
Ideally, you should remove the directories immediately after deleting the files, rather than doing two passes with os.walk
import sys
import os
for dir, subdirs, files in os.walk(sys.argv[1], topdown=False):
for name in files:
if not(name.endswith(".pdf")):
os.remove(os.path.join(dir, name))
# check whether the directory is now empty after deletions, and if so, remove it
if len(os.listdir(dir)) == 0:
os.rmdir(dir)
For empty folders deletion you can use this snippet.
It can be combined with some files deletion, but as last run should be used as is.
import os
def drop_empty_folders(directory):
"""Verify that every empty folder removed in local storage."""
for dirpath, dirnames, filenames in os.walk(directory, topdown=False):
if not dirnames and not filenames:
os.rmdir(dirpath)
remove all empty folders
import os
folders = './A/' # directory
for folder in list(os.walk(folders)) :
if not os.listdir(folder[0]):
os.removedirs(folder[0])

All Files in Dir & Sub-Dir

I would like to find all the files in a directory and all sub-directories.
code used:
import os
import sys
path = "C:\\"
dirs = os.listdir(path)
filename = "C.txt"
FILE = open(filename, "w")
FILE.write(str(dirs))
FILE.close()
print dirs
The problem is - this code only lists files in directories, not sub-directories. What do I need to change in order to also list files in subdirectories?
To traverse a directory tree you want to use os.walk() for this.
Here's an example to get you started:
import os
searchdir = r'C:\root_dir' # traversal starts in this directory (the root)
for root, dirs, files in os.walk(searchdir):
for name in files:
(base, ext) = os.path.splitext(name) # split base and extension
print base, ext
which would give you access to the file names and the components.
You'll find the functions in the os and os.path module to be of great use for this sort of work.
This function will help you: os.path.walk() http://docs.python.org/library/os.path.html#os.path.walk

Categories