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

相关推荐
卜锦元13 分钟前
Golang项目开发过程中好用的包整理归纳(附带不同包仓库地址)
开发语言·后端·golang
Tony Bai4 小时前
“我曾想付钱给 Google 去工作”—— Russ Cox 深度访谈:Go 的诞生、演进与未来
开发语言·后端·golang
sali-tec4 小时前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
路边草随风5 小时前
milvus向量数据库使用尝试
人工智能·python·milvus
hnlgzb5 小时前
安卓app开发,如何快速上手kotlin和compose的开发?
android·开发语言·kotlin
newobut5 小时前
vscode远程调试python程序,基于debugpy库
vscode·python·调试·debugpy
无敌最俊朗@5 小时前
STL-deque面试剖析(面试复习4)
开发语言
APIshop6 小时前
用 Python 把“API 接口”当数据源——从找口子到落库的全流程实战
开发语言·python
Java Fans6 小时前
Qt Designer 和 PyQt 开发教程
开发语言·qt·pyqt
RwTo6 小时前
【源码】-Java线程池ThreadPool
java·开发语言