python files and folders batch operations summary

python folder batch operations

Delete a file folder

for i in os.listdir(path):   ##用于返回指定的文件夹包含的文件或文件夹的名字的列表
    path_file = os.path.join(path,i)    ##连接两个或更多的路径名组件
    if os.path.isfile(path_file):       ##判断是否为文件
        os.remove(path_file)            ##对文件进行删除 
    else:                               ##如果为文件夹继续进行判断
        for f in os.listdir(path_file):  ##二级文件夹下文件无法删除,下叙代码进行改进
            path_file2 =os.path.join(path_file,f)
        if os.path.isfile(path_file2):
            os.remove(path_file2)        

Delete a folder and secondary folder file

def  del_file(path):
    for i in os.listdir(path):
         path_file = os.path.join(path,i) 
    if os.path.isfile(path_file):
         os.remove(path_file)
    else:
         del_file(path_file)     ##如果不是文件,对文件夹继续进行del_file函数
 ##执行
  path='E:\垃圾分类\文件夹'
del_file(path)  

Delete folder txt file

def  del_txt(path):   ##定义删除txt文件函数
    for i in os.listdir(path):    
        path_file = os.path.join(path,i)
        file=os.path.splitext(path_file)
        filename,type=file
        if type=='.txt':     ##如果文件后缀为txt,则删除文件
             os.remove(path_file)  
  ##执行
  path1='E:\\垃圾分类\\华为数据\\train_data_v2'
del_txt(path1)

Folder pictures renumbered (named)

import sys
def rename():
    path=input("请输入路径(例如D:\\picture):")
    name=input("请输入开头名:")
    startNumber=input("请输入开始数:")
    fileType=input("请输入后缀名(如 .jpg、.txt等等):")
    count=0
    i=1
    filelist=os.listdir(path)
    for files in filelist:
        Olddir=os.path.join(path,files)
        if os.path.isdir(Olddir):
            continue
        Newdir=os.path.join(path,name+str("%03d" % i)+'-'+str(count+int(startNumber))+fileType)
        os.rename(Olddir,Newdir)
        if count==74:
            count=0
            i=i+1
        else:
            count=count+1
    print("一共修改了"+str((i-1)*78+count)+"个文件")
    rename()

Batch create folders


def creDir():
   ## 数字前补0创建文件夹002,003...
    root = 'E:\\picture\\'
    i = 1
    for j in range(196):
        k = 'name'+"%03d" % i   ##左边补零的等宽格式
        file_name = root + str(k)
        os.mkdir(file_name)
        i=i+1
##原文链接:https://blog.csdn.net/u014421797/article/details/83242997

The specified files in the specified folder

##将指定文件放入指定文件夹中,文件夹与文件在同一路径下,且文件夹名称与文件前缀一致
for folderName, subfolders, filenames in os.walk('E:\\picture'):   ##文件与文件夹在同一路径
   for subfolder in subfolders:
       for filename in filenames:
           if filename[:7] == subfolder[:7]:
               try:
                   shutil.move(folderName + '\\'+ filename, folderName + '\\'+ subfolder)
               except OSError:
                   pass

Batch delete the specified folder

def  del_folder(path):              ##定义删除指定名称文件夹函数
   for i in os.listdir(path):      
       path_folder = os.path.join(path,i)  ##将文件夹名称保存在path_folder中
       root = 'E:\\每人任务夹\\'       
       j = 1
       for l in range(196):               ##编辑想要删除文件夹名称
           k ='E:\\每人任务夹\\name'+"%03d" % j
           j=j+1
           if path_folder==k:            ##判断是否有该文件夹,如果有则删除 
               shutil.rmtree(path_folder)
##执行
path2='E:\\每人任务夹\\'
del_folder(path2)

If the ## code is running can not accidentally lost retrieve history
python accessible from anaconda prompt operation, the ratio is more convenient cmd
written directly in the path of the anaconda prompt, enters in the path, as follows
Here Insert Picture Description

12.3 Record

(To be separated from the previous record, I can not remember what wrote above, to re)

Create a folder named data in the name

Read package file

File data into 330 categories junk folder name, for example: a banana peel, plastic bags, etc.

import os
import shutil
import pandas as pd
import numpy as np
data=pd.read_csv('E:\\任务分配\\分类表格.csv',sep=',',names=['name'])  ##names为文件特征命名

Defined functions, create folders

def creDir():
    root = 'E:\\任务分配\\合并图片\\图片分类1\\'  ##文件夹创建路径
    i=0
    for j in range(333):
        file_name = root + str(data.name[i])
        os.mkdir(file_name)
        i=i+1

creDir()

The picture merge different folder in the same subfolder

(Example: a banana peel under name1 folder picture combined with the next name2 banana peel folder, the code for the 333 class folder batch merge, using the file name as the index to find)

SOURCE_DIR = r'E:\任务分配\合并图片\图片'
root= 'E:\\任务分配\\合并图片\\图片分类1\\'
##rb = open_workbook('m:\\1.xls')
i=0
for j in range(333):
    COPY_DIR =data.name[i]
    TARGET_DIR=root+str(data.name[i])
    for dir_path, sub_dirs, files in os.walk(SOURCE_DIR, True):
        if os.path.split(dir_path)[-1] == COPY_DIR:
            for file in files:
                shutil.copyfile(os.path.join(dir_path, file), \
                            os.path.join(TARGET_DIR, file))
  ##                          ws = rb.get_sheet(0)
    ##                        ws.write(0,i,)
      ##                      wb.save('m:\\1.xls')
                            
    i=i+1

The different folders erupted in the same folder name picture merge into the same folder

(Looking source_dir with copy_dir the same file name, to copy all put in target_dir)

##函数编辑
SOURCE_DIR = r'E:\任务分配\合并图片\图片'
TARGET_DIR=r'E:\\任务分配\\合并图片\\图片分类\\零食'
COPY_DIR ='零食'
for dir_path, sub_dirs, files in os.walk(SOURCE_DIR, True):
       if os.path.split(dir_path)[-1] == COPY_DIR:
            for file in files:
                shutil.copyfile(os.path.join(dir_path, file), \
                            os.path.join(TARGET_DIR, file))

##运行
SOURCE_DIR = r'E:\任务分配\合并图片\图片'
dir_path=os.walk(SOURCE_DIR, False)

Delete the specified file path

##读入有争议图片
data1=pd.read_csv('E:\\任务分配\\有争议图片.csv',sep=',',names=['file','name'])
data1.file[1]
 
##删除文件
i=1
for j in range(44):
    root='E:\\任务分配\\合并图片\\图片分类\\'
    file_name=root+str(data1.file[i])+'\\'+str(data1.name[i])+'.jpg';
    os.remove(file_name)
    i=i+1

Bulk copy files to a specified folder

##读入有争议图片
from shutil import copyfile
data2=pd.read_csv('E:\\任务分配\\最终有争议图片##批量复制文件到指定文件夹
##创建特定文件夹
i=1
root='E:\任务分配\最终有争议图片\有争议图片\\'
root1='E:\任务分配\最终有争议图片\\最终有争议'    
##放置有争议图片
for j in range(912):
    file_name=root+str(data2.file[i][0:6])+'\\'+str(data2.file[i])+'.jpg';
    file=root1+'\\'+str(data2.file[i])+'.jpg';
    shutil.copyfile(file_name,file)
    i=i+1csv',sep=',',names=['file','name1','name2','name3'])
data2.file[0]

Published 20 original articles · won praise 3 · Views 3536

Guess you like

Origin blog.csdn.net/qq_41858657/article/details/101711525