Guest User

Untitled

a guest
May 26th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. import os
  5. import argparse
  6. import shutil
  7.  
  8. _DESCRIPTION = "Strip extended characters from all non-hidden files in a path."
  9.  
  10. def _get_args():
  11. parser = \
  12. argparse.ArgumentParser(
  13. description=_DESCRIPTION)
  14.  
  15. parser.add_argument(
  16. 'root_path',
  17. help="Root path")
  18.  
  19. parser.add_argument(
  20. '-bp', '--backup-path',
  21. help="Path to copy originals to before modifying")
  22.  
  23. args = parser.parse_args()
  24. return args
  25.  
  26. def _main():
  27. args = _get_args()
  28.  
  29. ignores = []
  30. len_ = len(args.root_path)
  31. for path, folders, files in os.walk(args.root_path):
  32. rel_path = path[len_ + 1:]
  33.  
  34. for folder in folders:
  35. if folder[0] == '.':
  36. ignores.append(os.path.join(rel_path, folder))
  37.  
  38. if rel_path in ignores:
  39. continue
  40.  
  41. for filename in files:
  42. filepath = os.path.join(path, filename)
  43. with open(filepath, 'rb') as f:
  44. data = f.read()
  45.  
  46. parts = []
  47. last_change = None
  48. fixes = 0
  49. for i, c in enumerate(data):
  50. try:
  51. o = ord(c)
  52. except TypeError:
  53. o = c
  54.  
  55. if o <= 0x7f:
  56. continue
  57.  
  58. if last_change is None:
  59. parts.append(data[:i])
  60. else:
  61. parts.append(data[last_change + 1:i])
  62.  
  63. parts.append('.')
  64. last_change = i
  65.  
  66. if parts:
  67. print("{} characters stripped. Updating [{}].".format(
  68. (len(parts) - 1) / 2, filepath[len(args.root_path) + 1:]))
  69.  
  70. if args.backup_path is not None:
  71. backup_path = os.path.join(args.backup_path, rel_path)
  72. backup_filepath = os.path.join(backup_path, filename)
  73. if os.path.exists(backup_path) is False:
  74. os.makedirs(backup_path)
  75.  
  76. with open(filepath, 'rb') as f:
  77. with open(backup_filepath, 'wb') as g:
  78. shutil.copyfileobj(f, g)
  79.  
  80. with open(filepath, 'wb') as f:
  81. f.write(''.join(parts))
  82.  
  83. _main()
Add Comment
Please, Sign In to add comment