Guest User

Untitled

a guest
Jan 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. # @File (label = "Output directory", style = "directory") output_directory
  2. import os
  3. import csv
  4. from ij.gui import YesNoCancelDialog
  5. from java.awt import Frame
  6.  
  7.  
  8. def main():
  9. """ImageJ Jython script testing for the existence of an output file before
  10. writing to that file location.
  11. Graceful exit if user chooses to cancel the operation.
  12. """
  13. try:
  14. output_filename = begin_output_file(output_directory)
  15. except KeyboardInterrupt:
  16. print("User cancelled script \
  17. to avoid overwriting existing output file")
  18. return
  19. # program continues...
  20.  
  21.  
  22. def begin_output_file(output_directory):
  23. """Writes output file, with option to cancel if overwriting existing file.
  24. Parameters
  25. ----------
  26. output_csv_directory : String directory path for the output file location.
  27. Returns
  28. -------
  29. csv_filename : String filepath to the output csv file.
  30. Raises
  31. ------
  32. KeyboardInterrupt
  33. User cancellation of analysis script
  34. to avoid overwriting existing output files.
  35. """
  36. csv_filename = os.path.join(str(output_directory), 'csv_filename.csv')
  37. error_msg = "User cancelled script to avoid \
  38. overwriting existing output files."
  39. if os.path.exists(csv_filename) is False: # file does not yet exist
  40. # write new file
  41. headers = ["header_1", "header_2", "header_3", "header_4"]
  42. with open(csv_filename, 'wb') as f:
  43. writer = csv.writer(f)
  44. writer.writerow(headers)
  45. return csv_filename
  46. elif os.path.exists(csv_filename) is True: # file already exists
  47. overwrite_files_dialog = YesNoCancelDialog(
  48. Frame(),
  49. "Overwrite file?",
  50. "Do you want to overwrite the existing csv file?"
  51. )
  52. if overwrite_files_dialog.yesPressed():
  53. print("Overwriting existing file...")
  54. # write new empty csv file
  55. with open(csv_filename, 'wb') as f:
  56. writer = csv.writer(f)
  57. writer.writerow(headers)
  58. return csv_filename
  59. elif overwrite_files_dialog.cancelPressed():
  60. raise KeyboardInterrupt(error_msg)
  61. else:
  62. raise KeyboardInterrupt(error_msg)
  63. return
  64.  
  65.  
  66. main()
  67. print("Finished")
Add Comment
Please, Sign In to add comment