如何获取appjar中saveBox的文件目录与文件名?
解决appjar saveBox获取文件目录与文件名的问题
你遇到的问题是因为设置了asFile=True,此时saveBox返回的是文件IO对象而非文件路径字符串。要获取目录和文件名,有两种可行方法:
方法1:从文件对象中提取路径
文件IO对象的name属性存储了完整文件路径,结合os.path.split()可以拆分出目录和文件名:
import os from appJar import gui def pressing(button): if button == "Create .txt file": # 获取文件对象 file_obj = app2.saveBox(title="File creator", fileName="", dirName="", fileExt=".txt", fileTypes="", asFile=True, parent=None) if file_obj: # 检查用户是否取消了对话框 # 获取完整文件路径 full_path = file_obj.name # 拆分目录和文件名 file_dir, file_name = os.path.split(full_path) print(f"文件目录:{file_dir}") print(f"文件名:{file_name}") # 向文件写入内容的示例 file_obj.write("这是写入的内容") file_obj.close() # 记得关闭文件对象 app2 = gui() app2.addButtons(["Create .txt file"], pressing) app2.go()
方法2:直接获取路径字符串
如果不需要直接操作文件对象,将asFile=False(默认值,可省略该参数),saveBox会直接返回完整文件路径字符串:
import os from appJar import gui def pressing(button): if button == "Create .txt file": # 获取完整文件路径 full_path = app2.saveBox(title="File creator", fileName="", dirName="", fileExt=".txt", fileTypes="", asFile=False, parent=None) if full_path: # 检查用户是否取消了对话框 # 拆分目录和文件名 file_dir, file_name = os.path.split(full_path) print(f"文件目录:{file_dir}") print(f"文件名:{file_name}") # 向文件写入内容的示例 with open(full_path, 'w', encoding='utf-8') as f: f.write("这是写入的内容") app2 = gui() app2.addButtons(["Create .txt file"], pressing) app2.go()
注意:要处理用户取消对话框的情况(此时返回值为None),避免后续代码报错。
内容的提问来源于stack exchange,提问作者iv1x
相关产品推荐
相关产品推荐

