SoFunction
Updated on 2024-11-12

python batch processing of files or folders

This article example for you to share the python batch processing file or folder specific code, for your reference, the details are as follows

# -*- coding: utf-8 -*-
import os,shutil
import sys
import numpy as np
########## Batch Delete Folders with Same Name in Different Folders #############
def arrange_file(dir_path0):
 for dirpath,dirnames,filenames in (dir_path0):
  if 'my_result' in dirpath:
   # print(dirpath)
   (dirpath)


########## Batch create new subfolders with same name under different folders and move files to subfolders #############
def arrange_file(dir_path0):
 for dirpath,dirnames,filenames in (dir_path0):
  for files in filenames:
   total_path = (dirpath,files)
   root_path,file_path = total_path.split(dir_path,1)
   if 'png' in file_path:
    new_file_path = '.' + file_path[:-9] + 'new_file_name/'
    # print(file_path)
    # print(new_file_path)
    # print(new_file_path + file_path[-9:])
    # if not (new_file_path):
    #  (new_file_path)
    # ('.' + file_path,new_file_path + file_path[-9:])

########## Batch delete eligible files in different folders ##################
def arrange_file(dir_path0):
 for dirpath,dirnames,filenames in (dir_path0):
  for files in filenames:
   total_path = (dirpath,files)
   # print(total_path)
   if 'jpg' in total_path and 'labels' in total_path:
    img = (total_path)
    if (img) == 0:
     print(total_path)
     (total_path)

########### Batch move files to upper level folder and delete current folder ########
def arrange_file(dir_path0):
 for dirpath,dirnames,filenames in (dir_path0):
  for files in filenames:
   total_path = (dirpath,files)
   root_path,file_path = total_path.split(dir_path0,1)
   # print(file_path[:-48])
   # return 0
   if 'jpg' in file_path:
    new_file_path = dir_path0 + file_path[:-48]
    (dir_path0 + file_path,new_file_path + file_path[-9:])

 for dirpath,dirnames,filenames in (dir_path0):
  file_path = ('./your_total_path')[1]
  if 'keywords' in file_path:
   # print(dirpath) 
   (dirpath)

if __name__=='__main__':
 dir_path0 = './your_total_path'
 arrange_file(dir_path0)

This is the whole content of this article.