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

相关推荐
楼兰公子37 分钟前
buildroot 在编译rust时裁剪平台类型数量的方法
开发语言·后端·rust
知识领航员1 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
吴声子夜歌1 小时前
Go——并发编程
开发语言·后端·golang
ooseabiscuit1 小时前
Laravel4.x:现代PHP框架的奠基之作
java·开发语言·php
c1s2d3n4cs2 小时前
Qt模仿nlohmann::json进行序列化和反序列化
开发语言·qt·json
如何原谅奋力过但无声2 小时前
【灵神高频面试题合集06-08】反转链表、快慢指针(环形链表/重排链表)、前后指针(删除链表/链表去重)
数据结构·python·算法·leetcode·链表
deephub2 小时前
2026 RAG 选型指南:Vector、Graph、Vectorless 该怎么挑
人工智能·python·大语言模型·rag
AiTop1003 小时前
Claude Code 推出 Agent View:命令行编程正式进入“多线程并发“时代
开发语言·人工智能·ai·aigc
jf加菲猫3 小时前
第21章 Qt WebEngine
开发语言·c++·qt·ui
码农-阿杰3 小时前
深入理解 synchronized 底层实现:从 HotSpot C++ 源码看对象锁与 Monitor 机制
开发语言·c++·