ift_convert.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import csv
  2. from pathlib import Path
  3. from itertools import chain
  4. class IFTConverter:
  5. def __init__(self, base_dir):
  6. self.config = {
  7. '_A_': {
  8. '1': self.import_config(base_dir + 'actuals_header.txt'),
  9. '2': self.import_config(base_dir + 'actuals_item.txt')
  10. },
  11. '_B_': {
  12. '010': self.import_config(base_dir + 'budget_line.txt')
  13. },
  14. '_C_': {
  15. '010': self.import_config(base_dir + 'commitment_line.txt')
  16. },
  17. '_K_': {
  18. '1': self.import_config(base_dir + 'controllingdoc_header.txt'),
  19. '2': self.import_config(base_dir + 'controllingdoc_item.txt')
  20. },
  21. '_P_': {
  22. '010': self.import_config(base_dir + 'plan_line.txt')
  23. }
  24. }
  25. def import_config(self, filename):
  26. with open(filename, 'r') as frh:
  27. return [(int(line['start']) - 1, int(line['start']) + int(line['length']) - 1)
  28. for line in csv.DictReader(frh, delimiter='\t')]
  29. def convert_dir(self, path):
  30. source_path = Path(path)
  31. target_path = source_path.parent.joinpath('prod_csv')
  32. for filename in source_path.glob('*.txt'):
  33. print(filename.name)
  34. self.convert_file(filename, target_path)
  35. def convert_file(self, source, target_path):
  36. cfg = self.conversion_config(source.name)
  37. target = target_path.joinpath(source.name[:-4] + '.csv')
  38. content = {}
  39. last_key = list(cfg.keys())[-1]
  40. with open(source, 'r', errors='ignore') as frh:
  41. with open(target, 'w') as fwh:
  42. for line in frh.readlines():
  43. for key, rules in cfg.items():
  44. if line.startswith(key):
  45. content[key] = self.convert_line(line, rules)
  46. break
  47. if line.startswith(last_key):
  48. fwh.write('\t'.join(chain(*content.values())) + '\n')
  49. def convert_line(self, line, rules):
  50. return [line[rule[0]:rule[1]].strip() for rule in rules]
  51. def conversion_config(self, filename):
  52. for key, cfg in self.config.items():
  53. if key in filename:
  54. return cfg
  55. return {
  56. '0': []
  57. }
  58. def main():
  59. ift_conv = IFTConverter('/home/robert/projekte/python/dbtools/config/IFT/')
  60. ift_conv.convert_dir('/home/robert/projekte/python/BMW_Wien/IFT/prod')
  61. if __name__ == '__main__':
  62. main()