Skip to content

Instantly share code, notes, and snippets.

@GenevieveBuckley
Last active January 9, 2018 04:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save GenevieveBuckley/d9a7238b47d501063a3ddd782067b151 to your computer and use it in GitHub Desktop.
ImageJ Jython script testing for the existence of an output file before writing to that file location. Graceful exit if user chooses to cancel the operation.
# @File (label = "Output directory", style = "directory") output_directory
import os
import csv
from ij.gui import YesNoCancelDialog
from java.awt import Frame
def main():
"""ImageJ Jython script testing for the existence of an output file before
writing to that file location.
Graceful exit if user chooses to cancel the operation.
"""
try:
output_filename = begin_output_file(output_directory)
except KeyboardInterrupt:
print("User cancelled script \
to avoid overwriting existing output file")
return
# program continues...
def begin_output_file(output_directory):
"""Writes output file, with option to cancel if overwriting existing file.
Parameters
----------
output_csv_directory : String directory path for the output file location.
Returns
-------
csv_filename : String filepath to the output csv file.
Raises
------
KeyboardInterrupt
User cancellation of analysis script
to avoid overwriting existing output files.
"""
csv_filename = os.path.join(str(output_directory), 'csv_filename.csv')
error_msg = "User cancelled script to avoid \
overwriting existing output files."
if os.path.exists(csv_filename) is False: # file does not yet exist
# write new file
headers = ["header_1", "header_2", "header_3", "header_4"]
with open(csv_filename, 'wb') as f:
writer = csv.writer(f)
writer.writerow(headers)
return csv_filename
elif os.path.exists(csv_filename) is True: # file already exists
overwrite_files_dialog = YesNoCancelDialog(
Frame(),
"Overwrite file?",
"Do you want to overwrite the existing csv file?"
)
if overwrite_files_dialog.yesPressed():
print("Overwriting existing file...")
# write new empty csv file
with open(csv_filename, 'wb') as f:
writer = csv.writer(f)
writer.writerow(headers)
return csv_filename
elif overwrite_files_dialog.cancelPressed():
raise KeyboardInterrupt(error_msg)
else:
raise KeyboardInterrupt(error_msg)
return
main()
print("Finished")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment