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 小时前
【2025 年最新版】Java JDK 安装与环境配置教程(附图文超详细,Windows+macOS 通用)
java·开发语言·windows·macos·jdk
二哈喇子!5 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!5 小时前
空指针异常
开发语言
咚为5 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
jaray5 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
%xiao Q5 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang5 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Traced back5 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
sin22015 小时前
MyBatis的执行流程
java·开发语言·mybatis
web3.08889995 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python