Search code examples
pythonpyqtqfiledialog

QFileDialog crashing on cancel


I have an issue when closing QFileDialog.getSaveFileName. If I choose to cancel and not follow through with saving the file, my program crashes.

I understand that the statement will always be True since the getSaveFileName() function always returns a tuple, and I should be able to solve this issue with an If function, but I'm very new to programming and this has me stumped.

Any help would be greatly appreciated.

# Print List
CoOrdinates = ['CL', RoundedSOL_E_1, RoundedSOL_N_1, RoundedEOL_E_1, RoundedEOL_N_1]
Headers = ['Line Name', 'SOL_E', 'SOL_N', 'EOL_E', 'EOL_N']
print(Headers)
print(CoOrdinates)
save = QFileDialog.getSaveFileName(None, 'Save As', 'Line Plan.csv')

with open(save[0], 'a', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(Headers)
    writer.writerow(CoOrdinates)

Solution

  • When you choose to cancel the parameter that returns the filename it is an empty string so you can not open a file and therefore it throws the error, so you have to add a verification:

    CoOrdinates = ['CL', RoundedSOL_E_1, RoundedSOL_N_1, RoundedEOL_E_1, RoundedEOL_N_1]
    Headers = ['Line Name', 'SOL_E', 'SOL_N', 'EOL_E', 'EOL_N']
    print(Headers)
    print(CoOrdinates)
    filename, _ = QFileDialog.getSaveFileName(None, 'Save As', 'Line Plan.csv')
    if filename:
        with open(filename, 'a', newline='') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(Headers)
            writer.writerow(CoOrdinates)