Advertisement
Guest User

Untitled

a guest
Sep 26th, 2022
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import configparser
  4. from collections import OrderedDict
  5.  
  6. def save_comments(config_file):
  7. # find and log comments and more than one blank line in a row
  8. with open('test.ini', 'r') as f:
  9. content = f.readlines()
  10.  
  11. test = ('#', ';')
  12. blank = False
  13. # an ordered dictionary must be used to insert from the start of the file
  14. # otherwise the insertion points will be off if you use a dict
  15. comments = OrderedDict() # create the ordered dictionary
  16. # check for empty line after a comment and add that to the comment map
  17. for index, line in enumerate(content):
  18. if not line.startswith(test) and line.strip() != '':
  19. comment = False
  20. if line.startswith(test): # a comment
  21. comments[index] = line
  22. comment = True
  23. if line.strip() == '':
  24. if blank or comment: # second blank line
  25. comments[index] = line
  26. print('blank')
  27. blank = True
  28. else:
  29. blank = False
  30. return comments
  31.  
  32. def restore_comments(config_file, comment_map):
  33. """Write comments to config file at their original indices"""
  34. with open(config_file, 'r') as file:
  35. lines = file.readlines()
  36. for (index, comment) in comment_map.items():
  37. lines.insert(index, comment)
  38. with open(config_file, 'w') as file:
  39. file.write(''.join(lines))
  40.  
  41. config_file = 'test.ini'
  42. comment_map = save_comments(config_file)
  43. for key, value in comment_map.items():
  44. print(key, value)
  45.  
  46. # open config file and load it into configparser
  47. with open(config_file, 'r') as file:
  48. config = configparser.ConfigParser()
  49. config.optionxform = str
  50. config.read_string(file.read())
  51. # change every value in the config file to "CLASSIFIED"
  52. for section in config.sections():
  53. for key, value in config.items(section):
  54. config.set(section, key, "Changed")
  55. # write the new config to the config file
  56. with open(config_file, 'w') as file:
  57. config.write(file)
  58. # put the comments back in their original indices
  59. restore_comments(config_file, comment_map)
  60. print('Done')
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement