error de Python: xlsxwriter.exceptions.FileCreateError: [Errno 2] No existe el fichero o directorio: ''

devinxxxd;

Lo que estoy tratando de hacer:

Estoy tratando de guardar un archivo utilizando filedialog. La parte de ahorro funciona bien, pero si hago clic en Cancelar en el cuadro de diálogo de elegir no guardar, me sale este error. ¿Cómo se puede eliminar este error?

Error que estoy recibiendo:

Exception in Tkinter callback

FileNotFoundError: [Errno 2] No such file or directory: ''

During handling of the above exception, another exception occurred:


xlsxwriter.exceptions.FileCreateError: [Errno 2] No such file or directory: ''

A continuación se muestra el código:

import xlsxwriter
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog

def save():
    filename = filedialog.asksaveasfilename(filetypes=[("Excel files", ".xlsx .xls")],defaultextension='.xlsx')
    workbook = xlsxwriter.Workbook(filename)
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', 'Common Information') 
    worksheet.write('A2', 'Circumference of Tank')
    worksheet.write('C2', 'Height of Tank')
    worksheet.write('A3', 'Minimum Thickness of Tank')
    worksheet.write('C3', 'Maximum Thickness of Tank')   

    workbook.close()  

window = tk.Tk()
window.configure(background='white')

ws = window.winfo_screenwidth()
hs = window.winfo_screenheight()
w = 700 # width for the Tk root
h = 585  # height for the Tk root
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)

window.geometry('%dx%d+%d+%d' % (w, h, x, y))   

canvas = tk.Canvas(window,bg="white",width=700, height=585, highlightthickness=0)
canvas.pack()


save1 = ttk.Button(canvas, text='Save', command= lambda: save())
canvas.create_window(15, 15, window=save1, anchor=tk.NW)


window.resizable(False, False)
window.mainloop()
jizhihaoSAMA:

Su savefunción será llamada después de pulsar el botón.

filename = filedialog.asksaveasfilename(filetypes=[("Excel files", ".xlsx .xls")],defaultextension='.xlsx')
....

Porque cuando se deja de seleccionar la ruta de acceso, el nombre del archivo será (se trata de un strtipo, pero su longitud == 0) .Y workbook = xlsxwriter.Workbook(filename)elevará Excepción.

Por lo que debe utilizar una ifdeclaración antes de guardar el archivo xlsx.

Y la save()función debe ser:

def save():
    filename = filedialog.asksaveasfilename(filetypes=[("Excel files", ".xlsx .xls")],defaultextension='.xlsx')
    if filename:
        workbook = xlsxwriter.Workbook(filename)
        worksheet = workbook.add_worksheet()
        worksheet.write('A1', 'Common Information')
        worksheet.write('A2', 'Circumference of Tank')
        worksheet.write('C2', 'Height of Tank')
        worksheet.write('A3', 'Minimum Thickness of Tank')
        worksheet.write('C3', 'Maximum Thickness of Tank')

        workbook.close()

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=292114&siteId=1
Recomendado
Clasificación