Код: Выделить всё
import os
from openpyxl import load_workbook
import datetime
def extract_new_file_names(folder_path):
new_file_names = {}
for filename in os.listdir(folder_path):
if filename.endswith(".xlsx"):
file_path = os.path.join(folder_path, filename)
new_filename = extract_file_info(file_path)
new_file_names[file_path] = new_filename
return new_file_names
def extract_file_info(file_path):
wb = load_workbook(filename=file_path, read_only=True)
sheet = wb.active
# Extract information from the workbook
acronym = file_path.split("_")[0] # Get acronym from filename
date_cell = sheet['B4'].value # Get date from cell B4
gl_text = sheet['D6'].value # Get GL text from cell D6
wb.close()
# Process the extracted information and return the required data
formatted_date = datetime.datetime.strptime(date_cell, "%m/%d/%Y").strftime("%m-%d-%y")
bank_account = gl_text.split("- ", 1)[1]
return f"{acronym}-{formatted_date} {bank_account} recon.xlsx"
def rename_files(new_file_names):
for old_file_path, new_filename in new_file_names.items():
rename_file(old_file_path, new_filename)
def rename_file(old_file_path, new_filename):
# Rename the file
try:
os.rename(old_file_path, os.path.join(os.path.dirname(old_file_path), new_filename))
print(f"File {old_file_path} renamed to {new_filename}")
except Exception as e:
print(f"Failed to rename file {old_file_path}: {e}")
folder_path = "C:\\Folder\\Path\\Is\\Here"
new_file_names = extract_new_file_names(folder_path)
rename_files(new_file_names)
Код: Выделить всё
def rename_file(old_file_path, new_filename):
for proc in psutil.process_iter():
if "EXCEL.EXE" in proc.name():
proc.kill()
try:
os.rename(old_file_path, os.path.join(os.path.dirname(old_file_path), new_filename))
print(f"File {old_file_path} renamed to {new_filename}")
except Exception as e:
print(f"Failed to rename file {old_file_path}: {e}")
Подробнее здесь: https://stackoverflow.com/questions/784 ... -in-folder