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

相关推荐
小辉懂编程8 分钟前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
醍醐三叶1 小时前
C++类与对象--2 对象的初始化和清理
开发语言·c++
Magnum Lehar2 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
Mcworld8572 小时前
java集合
java·开发语言·windows
成功人chen某2 小时前
配置VScodePython环境Python was not found;
开发语言·python
2301_786964363 小时前
EXCEL Python 实现绘制柱状线型组合图和树状图(包含数据透视表)
python·microsoft·excel
skd89993 小时前
小蜗牛拨号助手用户使用手册
python
「QT(C++)开发工程师」3 小时前
STM32 | FreeRTOS 递归信号量
python·stm32·嵌入式硬件
海绵宝宝贾克斯儿3 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01123 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式