[英]Recording the names of pictures from certain folders in Excel using Python
I need to write the names of photos from a certain folder in 2 columns of an excel file, the writing should be gradual, that is, A1:B1, A2:B2 and so on我需要在excel文件的2列中写入来自某个文件夹的照片名称,写入应该是渐进的,即A1:B1,A2:B2等
I would appreciate any help or any information that would help me我将不胜感激任何帮助或任何对我有帮助的信息
You should look at How do I list all files of a directory?您应该查看如何列出目录的所有文件? and create a list of the filenames from the dir using os library并使用 os 库从 dir 创建文件名列表
you will also as stated by BigBen need to use a library that writes to Excel files.如BigBen所述,您还需要使用写入 Excel 文件的库。 You could also write the list to a dataframe before writing that dataframe to an excel file在将 dataframe 写入 excel 文件之前,您还可以将列表写入 dataframe
Assuming all the files in the Pictures directory have the same naming format, this should work:假设 Pictures 目录中的所有文件都具有相同的命名格式,这应该可以工作:
import os
import openpyxl
from openpyxl.styles import Border, Side, Alignment, Font
# Get a list of the filenames in the directory
filenames = os.listdir(r"C:\Users\Dwigt Rortugal\Desktop\Pictures")
# Used to sort the list of filenames by the number between "-" and ".png"
def get_filename_number(filename):
left = filename.find("-") + 1
right = filename.find(".png", left)
return int(filename[left:right])
# Sort the filenames by the number between "-" and ".png"
filenames.sort(key=get_filename_number)
# Create a new spreadsheet
wb = openpyxl.Workbook()
ws = wb.active
# Create the 2 column headers - bold, centered, with a border
font = Font(bold=True)
alignment = Alignment(horizontal='center')
side = Side(border_style="thin")
border = Border(left=side, right=side, top=side, bottom=side)
cell = ws["A1"]
cell.value = "number1"
cell.border = border
cell.alignment = alignment
cell.font = font
cell = ws["B1"]
cell.value = "number2"
cell.border = border
cell.alignment = alignment
cell.font = font
# Make the columns wider
ws.column_dimensions["A"].width = 14
ws.column_dimensions["B"].width = 14
# Write the filenames to the spreadsheet, starting at A1, then B1, A2, B2, etc
# Getting the correct cell row and column is achieved by using divmod
columns = 2
starting_row = 2
starting_column = 1
for i, filename in enumerate(filenames):
row, column = divmod(i, columns)
ws.cell(row=row+starting_row, column=column+starting_column).value = filename
# Save the spreadsheet to disk
wb.save(r"C:\Users\Dwigt Rortugal\Desktop\Picture Filenames.xlsx")
# Open the new spreadsheet
os.startfile(r"C:\Users\Dwigt Rortugal\Desktop\Picture Filenames.xlsx")
This is the spreadsheet:这是电子表格:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.