line_endings.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """ Functions for converting from DOS to UNIX line endings
  2. """
  3. import os
  4. import re
  5. import sys
  6. def dos2unix(file):
  7. "Replace CRLF with LF in argument files. Print names of changed files."
  8. if os.path.isdir(file):
  9. print(file, "Directory!")
  10. return
  11. with open(file, "rb") as fp:
  12. data = fp.read()
  13. if '\0' in data:
  14. print(file, "Binary!")
  15. return
  16. newdata = re.sub("\r\n", "\n", data)
  17. if newdata != data:
  18. print('dos2unix:', file)
  19. with open(file, "wb") as f:
  20. f.write(newdata)
  21. return file
  22. else:
  23. print(file, 'ok')
  24. def dos2unix_one_dir(modified_files, dir_name, file_names):
  25. for file in file_names:
  26. full_path = os.path.join(dir_name, file)
  27. file = dos2unix(full_path)
  28. if file is not None:
  29. modified_files.append(file)
  30. def dos2unix_dir(dir_name):
  31. modified_files = []
  32. os.path.walk(dir_name, dos2unix_one_dir, modified_files)
  33. return modified_files
  34. #----------------------------------
  35. def unix2dos(file):
  36. "Replace LF with CRLF in argument files. Print names of changed files."
  37. if os.path.isdir(file):
  38. print(file, "Directory!")
  39. return
  40. with open(file, "rb") as fp:
  41. data = fp.read()
  42. if '\0' in data:
  43. print(file, "Binary!")
  44. return
  45. newdata = re.sub("\r\n", "\n", data)
  46. newdata = re.sub("\n", "\r\n", newdata)
  47. if newdata != data:
  48. print('unix2dos:', file)
  49. with open(file, "wb") as f:
  50. f.write(newdata)
  51. return file
  52. else:
  53. print(file, 'ok')
  54. def unix2dos_one_dir(modified_files, dir_name, file_names):
  55. for file in file_names:
  56. full_path = os.path.join(dir_name, file)
  57. unix2dos(full_path)
  58. if file is not None:
  59. modified_files.append(file)
  60. def unix2dos_dir(dir_name):
  61. modified_files = []
  62. os.path.walk(dir_name, unix2dos_one_dir, modified_files)
  63. return modified_files
  64. if __name__ == "__main__":
  65. dos2unix_dir(sys.argv[1])