self.files_1 = [] self.files_2 = [] # 获取self.file_path路径下的文件和文件夹 self.items = os.listdir(self.file_path) for item in self.items: # 判断是否为文件 if os.path.isfile(os.path.join(self.file_path, item)): # 判断文件扩展名是否在custom_order列表中 if os.path.splitext(item)[1] in self.custom_order: self.files_1.append(item) # 判断是否为文件夹 elif os.path.isdir(os.path.join(self.file_path, item)): # 打开文件夹并获取其中的文件 folder_path = os.path.join(self.file_path, item) folder_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f)) and os.path.splitext(f)[1] in self.custom_order] self.files_2.extend(folder_files) # 打印获取到的文件列表 # 对self.files_1按照self.custom_order排序 self.files_1 = sorted(self.files_1, key=lambda x: self.custom_order.index(os.path.splitext(x)[1])) self.files_2 = sorted(self.files_2, key=lambda x: self.custom_order.index(os.path.splitext(x)[1])) print(self.files_1) print(self.files_2)如何获取self.files_2的路径

时间: 2024-04-08 09:30:02 浏览: 14
要获取`self.files_2`中每个文件的完整路径,你可以在添加文件到`self.files_2`列表时保存文件的绝对路径。以下是修改后的代码示例: ```python self.files_1 = [] self.files_2 = [] self.items = os.listdir(self.file_path) for item in self.items: if os.path.isfile(os.path.join(self.file_path, item)): if os.path.splitext(item)[1] in self.custom_order: self.files_1.append(item) elif os.path.isdir(os.path.join(self.file_path, item)): folder_path = os.path.join(self.file_path, item) folder_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f)) and os.path.splitext(f)[1] in self.custom_order] self.files_2.extend(folder_files) self.files_1 = sorted(self.files_1, key=lambda x: self.custom_order.index(os.path.splitext(x)[1])) self.files_2 = sorted(self.files_2, key=lambda x: self.custom_order.index(os.path.splitext(x)[1])) print(self.files_1) print(self.files_2) ``` 这样,`self.files_2`列表中的每个元素都是文件的完整路径,包括文件夹路径和文件名。你可以使用`os.path.abspath()`函数获取文件的绝对路径。

相关推荐

import tkinter as tk import pandas as pd import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import os class ExcelPlotter(tk.Frame): def init(self, master=None): super().init(master) self.master = master self.master.title("图方便") self.file_label = tk.Label(master=self, text="Excel File Path:") self.file_label.grid(row=0, column=0, sticky="w") self.file_entry = tk.Entry(master=self) self.file_entry.grid(row=0, column=1, columnspan=2, sticky="we") self.file_button = tk.Button(master=self, text="Open", command=self.open_file) self.file_button.grid(row=0, column=3, sticky="e") self.plot_button = tk.Button(master=self, text="Plot", command=self.plot_data) self.plot_button.grid(row=1, column=2, sticky="we") self.name_label = tk.Label(master=self, text="Out Image Name:") self.name_label.grid(row=2, column=0, sticky="w") self.name_entry = tk.Entry(master=self) self.name_entry.grid(row=2, column=1, columnspan=2, sticky="we") self.save_button = tk.Button(master=self, text="Save", command=self.save_image) self.save_button.grid(row=2, column=3, sticky="e") self.figure = plt.figure(figsize=(5, 4), dpi=150) self.canvas = FigureCanvasTkAgg(self.figure, master=self) self.canvas.get_tk_widget().grid(row=4, column=0, columnspan=4, sticky="we") self.pack() def open_file(self): file_path = tk.filedialog.askopenfilename(filetypes=[("Excel Files", "*.xls")]) self.file_entry.delete(0, tk.END) self.file_entry.insert(tk.END, file_path) def plot_data(self): file_path = self.file_entry.get() if os.path.exists(file_path): data = pd.read_excel(file_path) plt.plot(data['波长(nm)'], data['吸光度'], 'k') plt.xlim(300, 1000) plt.xlabel('Wavelength(nm)', fontsize=16) plt.ylabel('Abs.', fontsize=16) plt.gcf().subplots_adjust(left=0.13, top=0.91, bottom=0.16) plt.savefig('Last Fig', dpi=1000) plt.show() def save_image(self): if self.figure: file_path = tk.filedialog.asksaveasfilename(defaultextension=".png") if file_path: self.figure.savefig(file_path) root = tk.Tk() app = ExcelPlotter(master=root) app.mainloop()帮我增加一个删除当前图像的功能

import tkinter as tk from tkinter import filedialog from PIL import Image, ImageTk import pytesseract class App: def __init__(self, master): self.master = master self.master.title("图像文字识别") self.master.geometry("600x400") self.path = "" self.text = "" self.label_title = tk.Label(self.master, text="请选择图片文件", font=("宋体", 20)) self.label_title.pack(pady=20) self.button_choose_file = tk.Button(self.master, text="选择图片", command=self.choose_file) self.button_choose_file.pack(pady=10) self.label_image = tk.Label(self.master) self.label_image.pack(pady=10) self.button_recognize = tk.Button(self.master, text="开始识别", command=self.recognize) self.button_recognize.pack(pady=10) self.textbox_result = tk.Text(self.master, font=("宋体", 14)) self.textbox_result.pack(pady=10) def choose_file(self): self.path = filedialog.askopenfilename(title="选择图片", filetypes=[("Image Files", "*.jpg *.png *.jpeg")]) self.label_title.configure(text="已选择图片:" + self.path) # 显示选择的图片 if self.path: img = Image.open(self.path) img = img.resize((300, 300)) img_tk = ImageTk.PhotoImage(img) self.label_image.configure(image=img_tk) self.label_image.image = img_tk def recognize(self): if self.path: # 调用pytesseract识别文字 self.text = pytesseract.image_to_string(Image.open(self.path), lang="eng+chi_sim") # 显示识别结果 self.textbox_result.delete('1.0', tk.END) self.textbox_result.insert(tk.END, self.text) else: self.label_title.configure(text="请选择图片文件!") root = tk.Tk() app = App(root) root.mainloop()上述代码的算法对比分析怎么写

import pandas as pd import datetimeimport tkinter as tkfrom tkinter import filedialogclass MyApplication(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("智能POS明细提取") self.pack() self.create_widgets() def create_widgets(self): self.label_1 = tk.Label(self, text="请选择Excel文件:") self.label_1.pack() self.file_button = tk.Button(self, text="选择文件", command=self.load_file) self.file_button.pack() self.label_2 = tk.Label(self, text="请选择提取内容:") self.label_2.pack() self.choice_var = tk.StringVar() self.choice_var.set("1") self.radio_1 = tk.Radiobutton(self, text="按省提取", variable=self.choice_var, value="1") self.radio_1.pack() self.radio_2 = tk.Radiobutton(self, text="全部提取", variable=self.choice_var, value="2") self.radio_2.pack() self.submit_button = tk.Button(self, text="提取数据", command=self.extract_data) self.submit_button.pack() self.quit_button = tk.Button(self, text="退出", command=self.master.quit) self.quit_button.pack() def load_file(self): self.file_path = filedialog.askopenfilename(title="选择Excel文件", filetypes=[("Excel files", "*.xlsx")]) def extract_data(self): now = datetime.datetime.now().strftime('%Y%m%d') data = pd.read_excel(self.file_path, dtype={'商户编号':str,'终端编号':str}) department_list = data['省份'].unique() choice = self.choice_var.get() if choice == '1': department_name = input('请输入省份名称:') if department_name in department_list: new_df = data[data['省份'] == department_name ] file_name = department_name + '智能POS明细' + now + '.xlsx' new_df.to_excel(file_name, index=False) else: print('无法找到该省份!') elif choice == '2': for department in department_list: new_df = data[data['省份'] == department] file_name = department + '智能POS明细' + now + '.xlsx' new_df.to_excel(file_name, index=False)root = tk.Tk()app = MyApplication(master=root)app.mainloop()

class ExcelApp: def init(self, master): self.master = master master.title("Excel App") # 获取屏幕的宽度和高度 screen_width = master.winfo_screenwidth() screen_height = master.winfo_screenheight() # 将窗口的大小设置为屏幕的大小 master.geometry("%dx%d" % (screen_width, screen_height)) # 创建菜单栏 menubar = tk.Menu(master) master.config(menu=menubar) # 创建文件菜单及其子菜单 filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="PA綫", command=lambda: self.load_excel("D:\點檢系統存放資料夾\點檢明細\點檢内容明細.xlsx", "PA綫")) filemenu.add_command(label="PB綫", command=lambda: self.load_excel("D:\點檢系統存放資料夾\點檢明細\點檢内容明細.xlsx", "PB綫")) filemenu.add_command(label="Excel 3", command=lambda: self.load_excel("excel3.xlsx")) menubar.add_cascade(label="點檢綫別", menu=filemenu) # 创建帮助菜单及其子菜单 helpmenu = tk.Menu(menubar, tearoff=0) helpmenu.add_command(label="关于", command=self.show_about) menubar.add_cascade(label="帮助", menu=helpmenu) # 创建工具栏 toolbar = tk.Frame(master, height=30) tk.Button(toolbar, text="打开", command=lambda: QueryWindow(tk.Toplevel(root))).pack(side=tk.LEFT, padx=2, pady=2) tk.Button(toolbar, text="保存", command=self.save_to_excel).pack(side=tk.LEFT, padx=2, pady=2) toolbar.pack(side=tk.TOP, fill=tk.X) # 创建左侧面板 self.panel_left = tk.Frame(master, width=150, bg='lightcyan') self.panel_left.pack(side=tk.LEFT, fill=tk.Y) # 创建右侧面板 self.panel_right = tk.Frame(master) self.panel_right.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)根據這個代碼儅用戶點擊打開按鈕時將打開一個新的窗口,在新的窗口可以根據日期,綫別查詢一個txt中相應數據内容,在添加一個可以下載按鈕,將用戶查詢的信息導入出來的代碼

修改以下代码使其能够输出模型预测结果: def open_image(self): file_dialog = QFileDialog() file_paths, _ = file_dialog.getOpenFileNames(self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg)") if file_paths: self.display_images(file_paths) def preprocess_images(self, image_paths): data_transform = transforms.Compose([ transforms.CenterCrop(150), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) self.current_image_paths = [] images = [] for image_path in image_paths: image = Image.open(image_path) image = data_transform(image) image = torch.unsqueeze(image, dim=0) images.append(image) self.current_image_paths.append(image_path) return images def predict_images(self): if not self.current_image_paths: return for i, image_path in enumerate(self.current_image_paths): image = self.preprocess_image(image_path) output = self.model(image) predicted_class = self.class_dict[output.argmax().item()] self.result_labels[i].setText(f"Predicted Class: {predicted_class}") self.progress_bar.setValue((i+1)*20) def display_images(self, image_paths): for i, image_path in enumerate(image_paths): image = QImage(image_path) image = image.scaled(300, 300, Qt.KeepAspectRatio) if i == 0: self.image_label_1.setPixmap(QPixmap.fromImage(image)) elif i == 1: self.image_label_2.setPixmap(QPixmap.fromImage(image)) elif i == 2: self.image_label_3.setPixmap(QPixmap.fromImage(image)) elif i == 3: self.image_label_4.setPixmap(QPixmap.fromImage(image)) elif i == 4: self.image_label_5.setPixmap(QPixmap.fromImage(image))

最新推荐

recommend-type

华为OD机试D卷 - 用连续自然数之和来表达整数 - 免费看解析和代码.html

私信博主免费获取真题解析以及代码
recommend-type

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg

Screenshot_2024-05-10-20-21-01-857_com.chaoxing.mobile.jpg
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

spring添加xml配置文件

1. 创建一个新的Spring配置文件,例如"applicationContext.xml"。 2. 在文件头部添加XML命名空间和schema定义,如下所示: ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

输出这段Python代码输出所有3位整数中,个位是5且是3的倍数的整数

``` for i in range(100,1000): if i%10 == 5 and i%3 == 0: print(i) ``` 输出结果: ``` 105 135 165 195 225 255 285 315 345 375 405 435 465 495 525 555 585 615 645 675 705 735 765 795 825 855 885 915 945 975 ```