如何解决Python中open函数读取含空格路径文件的报错问题
修复带空格文件路径的拖拽哈希计算程序错误
问题现象
开发支持文件拖拽生成SHA1哈希的Python GUI程序时,拖拽路径含空格的文件会触发以下错误:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\c9947515\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__ return self.func(*args) ^^^^^^^^^^^^^^^^ File "C:\Users\c9947515\Desktop\Phyton\pythonProject1\dosya hash.py", line 19, in on_drop with open(file_path, "rb") as file: ^^^^^^^^^^^^^^^^^^^^^ OSError: [Errno 22] Invalid argument: '{C:/Users/c9947515/Desktop/Wire Text.txt}'
从报错信息可见,文件路径被额外的大括号包裹,导致open()函数无法识别有效路径。
解决方案
tkinterdnd2在处理带空格的拖拽文件路径时,会自动用大括号包裹路径,需对event.data返回的字符串进行清理:
- 移除首尾的大括号、引号等多余字符
- 处理多文件拖拽场景(示例中取第一个文件)
修改后的完整代码
import tkinterdnd2 as tk import tkinter as tk2 import hashlib root = tk.Tk() root.title("File Hash Calculator") root.geometry("400x150") root.drop_target_register(tk.DND_FILES) def on_drop(event): # 清理路径:移除首尾特殊字符,多文件时取第一个 file_path = event.data.strip('{}"').split()[0] try: with open(file_path, "rb") as file: data = file.read() sha1_hash = hashlib.sha1(data).hexdigest() # 清空输入框后插入新哈希值 input_box.delete(0, tk2.END) input_box.insert(0, sha1_hash) except OSError as e: input_box.delete(0, tk2.END) input_box.insert(0, f"错误:{str(e)}") root.dnd_bind("<<Drop>>", on_drop) label = tk2.Label(root, text="拖拽文件到此处计算SHA1哈希值:") label.pack(pady=10) input_box = tk2.Entry(root, width=50) input_box.pack(pady=5) root.mainloop()
关键修改说明
- 路径清理:
strip('{}"')移除路径首尾的大括号和引号,解决带空格路径的包裹问题;split()[0]处理多文件拖拽,仅取第一个文件(如需支持多文件可调整逻辑) - 异常处理:捕获文件读取时的错误,在输入框显示提示信息,提升程序健壮性
- 输入框优化:每次计算前清空输入框,避免多次拖拽的哈希值叠加显示
内容的提问来源于stack exchange,提问作者Umut Ataman BeeX
相关产品推荐
相关产品推荐

