python弹出文件打开和保存的选择框

tkinter.filedialog 模块中的 askopenfilename 函数和 asksaveasfilename 函数来显示文件打开和保存的选择框。
这两个函数的作用都是返回一个文件名。如果选择了一个文件,则会返回文件的绝对路径,如果取消了选择,则返回空字符串
前者用来读时的 filename,后者用来写时保存的 filename。

选择文件例子

python 复制代码
from tkinter.filedialog import askopenfilename


# 弹出文件选择对话框选择一个文件
read_file_name = askopenfilename()
if read_file_name != '':
    print("you can read from " + read_file_name)

    file1 = open(read_file_name, "r", encoding="utf-8")
    s = file1.read()
    print(s)
else:
    print("你未选择一个文件")

手动选择文件的例子

python 复制代码
from tkinter.filedialog import asksaveasfilename

# 弹出文件选择对话框选择保存文件
write_file_name = asksaveasfilename()
if write_file_name != "":
    print("you can write data to " + write_file_name)
    
    with open(write_file_name, "w", encoding="utf-8") as file:
        file.write("你好中国")
else:
    print("你未选择一个文件")

end

相关推荐
小红帽2.015 分钟前
从ioutil到os:Golang在线客服聊天系统文件读取的迁移实践
服务器·开发语言·golang
Zafir20241 小时前
Qt实现TabWidget通过addTab函数添加的页,页内控件自适应窗口大小
开发语言·c++·qt·ui
阿巴~阿巴~1 小时前
深入解析C++非类型模板参数
开发语言·c++
集成显卡3 小时前
使用 Google 开源 AI 工具 LangExtract 进行结构化信息抽取
python·google·openai
久笙&3 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python·架构
小指纹3 小时前
河南萌新联赛2025第(六)场:郑州大学
java·开发语言·数据结构·c++·算法
不甘懦弱4 小时前
阿里云搭建flask服务器
服务器·python·flask
赵英英俊4 小时前
Python day51
人工智能·pytorch·python
律品4 小时前
pytest的前置与后置
开发语言·python·pytest
飞翔的佩奇4 小时前
【完整源码+数据集+部署教程】遥感森林砍伐检测系统源码和数据集:改进yolo11-SWC
python·yolo·计算机视觉·数据集·yolo11·遥感森林砍伐检测