Use python to read the picture name of the picture in the folder and write it into the excel form

Sometimes, we need to read the picture name and write it into the table, so as to combine with other information of the picture for further analysis.
Suppose, now you want to read the origin_file folder stored in the E disk, read the picture name inside and write it into the excel file img.xlsx.
Stored in the origin_file folder of the E drive
First, you need to read the image folder path

import pandas as pd
import os 
os.chdir('E:\\')
#1.读取图片文件夹路径
path='origin_file'

Then, pandas creates a blank excel file "img.xlsx"

#2.建立空白excel文件“img.xlsx”
writer=pd.ExcelWriter("img.xlsx")

Then, iterate through the files in the pictures folder and write the file names into a new list

#3.将图片文件夹里的文件名写入新的列表
#3.1遍历图片文件夹
for root,dirs,files in os.walk(path):
#os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
list=[]             #建立新的列表list
#3.2遍历文件list里的所有的图片文件写入新列表list中
	for file in files:
		file=file.rstrip(".jpg")          #将图片名末尾的“.jpg”去掉
		list.append(file)                 #将图片名加入新列表list中        

Then, nest the list list into the dictionary data, convert it into a dataframe format and store it in the excel created at the beginning

#4.将列表list嵌套进字典dict_中
dict_={
    
    'filename':list}   #键名为新建表格的字段名,值为以图片名为元素的列表
#5.转换成dataframe格式
df=pd.DataFrame(dict_)
#6.储存在开始建立的excel中
df.to_excel(writer,'sheet1',startcol=0,index=False )  #工作表名称为“sheet1”,开始列为第一列,不需要索引
#7.保存文件
writer.save()

The picture name of the picture in the folder is written into the excel table.
The picture name is written into the excel sheetSummary of ideas:
read the target folder - create a new excel - write the picture name into the list - convert the list nested dictionary into a dataframe format - save in The complete code of excel
is as follows:

import pandas as pd
import os 
os.chdir('E:\\')
#1.读取图片文件夹路径
path='origin_file'
#2.建立空白excel文件“img.xlsx”
writer=pd.ExcelWriter("img.xlsx")
#3.将图片文件夹里的文件名写入新的列表
#3.1遍历图片文件夹
for root,dirs,files in os.walk(path):
#os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
# root 表示当前正在访问的文件夹路径
# dirs 表示该文件夹下的子目录名list
# files 表示该文件夹下的文件list
list=[]             #建立新的列表list
#3.2遍历文件list里的所有的图片文件写入新列表list中
	for file in files:
		file=file.rstrip(".jpg")          #将图片名末尾的“.jpg”去掉
		list.append(file)                 #将图片名加入新列表list中        
#4.将列表list嵌套进字典dict_中
dict_={
    
    'filename':list}   #键名为新建表格的字段名,值为以图片名为元素的列表
#5.转换成dataframe格式
df=pd.DataFrame(dict_)
#6.储存在开始建立的excel中
df.to_excel(writer,'sheet1',startcol=0,index=False )  #工作表名称为“sheet1”,开始列为第一列,不需要索引
#7.保存文件
writer.save()

It is not easy to create, please like, bookmark, and support it!

Guess you like

Origin blog.csdn.net/weixin_47970003/article/details/121776187