line_endings.py 2.0 KB

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