使用Tkinter上传Excel后文件0字节、无法打开问题求助
核心问题原因
- 提供的代码仅在目标路径创建了空文件,没有读取原Excel文件的内容写入新文件,因此生成的文件大小为0字节,自然无法正常打开
- 代码中
...core/files/为相对路径写法,若运行时工作目录不符合预期,还可能出现文件存储位置错误的问题,不过当前故障的核心诱因是未写入文件内容
修复代码示例
import os from tkinter import filedialog # 选择本地源Excel文件 filename = filedialog.askopenfilename(filetypes=[("Excel files","*.xlsx")]) if filename: fn = os.path.basename(filename) # 提前创建目标存储目录,避免目录不存在导致写入报错 os.makedirs('core/files', exist_ok=True) # 用os.path.join拼接路径,适配不同操作系统的路径分隔符规则 target_path = os.path.join('core/files', fn) # 同时打开源文件和目标文件,读写内容 with open(filename, 'rb') as source_file, open(target_path, 'wb') as target_file: target_file.write(source_file.read()) print(f'The file "{fn}" was uploaded successfully') else: print('No file was uploaded')
额外优化建议
- 采用
with语句管理文件操作,无需手动调用close()方法,即便读写过程中出现异常也能自动释放文件资源,避免泄露 - 若需要处理体积超过10MB的Excel文件,建议分块读写降低内存占用,示例代码如下:
chunk_size = 1 * 1024 * 1024 # 单次读取1MB内容 with open(filename, 'rb') as source_file, open(target_path, 'wb') as target_file: chunk = source_file.read(chunk_size) while chunk: target_file.write(chunk) chunk = source_file.read(chunk_size)
- 若对文件存储位置有严格要求,建议将目标路径改为绝对路径,避免相对路径受运行工作目录影响存错文件
内容的提问来源于stack exchange,提问作者Allen
相关产品推荐
相关产品推荐

