prepare_folder_for_save.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import os
  2. import argparse
  3. print('WARNING: this script change filenames')
  4. def dir_path(string):
  5. if os.path.isdir(string):
  6. return string
  7. else:
  8. raise NotADirectoryError(string)
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument('--dir', type=dir_path)
  11. args = parser.parse_args()
  12. if(not args.dir or len(args.dir) == 0):
  13. print('Mandatory --dir parameter')
  14. else:
  15. dir = args.dir
  16. tedi_files = list()
  17. list_dir = os.listdir(dir)
  18. for file in list_dir:
  19. if file.endswith(".te"):
  20. tedi_files.append(os.path.join(dir, file))
  21. if(len(tedi_files) == 1):
  22. print('Found tedi file, using it as index.te')
  23. os.rename(tedi_files[0], dir + 'index.te')
  24. img_files = list()
  25. i = 0
  26. line = ''
  27. f = open(os.path.join(dir, "index.te"), "r")
  28. lines = f.read()
  29. for file in os.listdir(dir):
  30. if not file.endswith(".te"):
  31. if lines.find(file) != -1:
  32. print('Renaming ' + file + ' to nibis style')
  33. lines = lines.replace('] ' + file + ')', '] image' + str(i) + ')')
  34. os.rename(dir + file, dir + 'image' + str(i))
  35. i += 1
  36. f.close()
  37. f = open(os.path.join(dir, "index.te"), "w")
  38. f.write(lines)
  39. f.close()
  40. else:
  41. if(dir + 'index.te' in tedi_files):
  42. print('Found multiple tedi files with a index.te file')
  43. f = open(os.path.join(dir, "index.te"), "r")
  44. lines = f.readlines()
  45. complete_text = ""
  46. for line in lines:
  47. if(len(line) > 0 and line[0] == '+'):
  48. try:
  49. print('Found inserted file: ' + line[1:-1])
  50. include = open(os.path.join(dir, line[1:-1]), "r")
  51. include_text = include.readlines()
  52. for new_line in include_text:
  53. complete_text += new_line
  54. include.close()
  55. print('Inserted file added to index.te')
  56. except:
  57. complete_text += line
  58. print('Failed inserted file')
  59. else:
  60. complete_text += line
  61. f.close()
  62. i = 0
  63. for file in os.listdir(dir):
  64. if not file.endswith(".te"):
  65. if file in complete_text:
  66. print('Renaming ' + file + ' to nibis style')
  67. complete_text = complete_text.replace('] ' + file + ')', '] image' + str(i) + ')')
  68. os.rename(dir + file, dir + 'image' + str(i))
  69. i += 1
  70. elif file not in "index.te":
  71. os.remove(os.path.join(dir, file))
  72. f = open(os.path.join(dir, "index.te"), "w")
  73. f.write(complete_text)
  74. f.close()
  75. else:
  76. print('If there are multiples tedi files, this script needs one named index.te to be the main one')