获取到了电脑所有软件,但是几百号人员,手动处理太麻烦,用python先读取文件内容,再把内容和文件名和一起保存到Excel表中,好统一处理。
from os import path, listdir
import chardet
import pandas as pd
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
def process_files():
global folder_path
save_file_name = '总数据.xlsx'
# 获取目标文件夹下所有txt文件的文件名
files = [path.join(folder_path, file) for file in listdir(folder_path) if file.endswith('.txt')]
# 初始化一个空的列表,用于存储数据
data = {'软件': [], '人员': []}
# 遍历每个文件
for your_file in files:
with open(your_file, 'rb') as file:
raw_data = file.read()
result = chardet.detect(raw_data)
# 使用检测到的编码格式来打开文件
encoding = result['encoding']
file_name = path.basename(your_file)
with open(your_file, 'r', encoding=encoding) as file:
for line in file:
data['软件'].append(line.strip())
file_nameB = path.splitext(file_name)[0]
data['人员'].append(file_nameB)
# 创建DataFrame
df = pd.DataFrame(data)
# 将DataFrame保存到Excel文件
output_file_path = path.join(folder_path, save_file_name)
try:
df.to_excel(output_file_path, index=False)
messagebox.showinfo("完成", f"数据已成功保存到 {save_file_name}")
except Exception as e:
messagebox.showerror("错误", f"保存文件时出现错误:{e}")
def select_folder():
global folder_path
folder_path = filedialog.askdirectory()
if folder_path:
start_button.config(state=tk.NORMAL)
# 创建主窗口
root = tk.Tk()
root.title("处理文件")
root.geometry('300x150')
# 文件夹路径和开始按钮
folder_path_label = tk.Label(root, text="选择文件夹:")
folder_path_label.pack(pady=10)
select_button = tk.Button(root, text="选择文件夹", command=select_folder)
select_button.pack()
start_button = tk.Button(root, text="开始处理文件", command=process_files, state=tk.DISABLED)
start_button.pack(pady=10)
root.mainloop()