python批量 unix、windows 文件格式互换

x33g5p2x  于2022-08-17 转载在 Python  
字(1.5k)|赞(0)|评价(0)|浏览(1167)
  1. import os
  2. import stat
  3. def change_dos_to_unix(path):
  4. g = os.walk(path)
  5. files = ['%s/%s' % (i[0], j) for i in g for j in i[-1]]
  6. for subpath in files:
  7. mode = os.stat(subpath)[stat.ST_MODE]
  8. if stat.S_ISDIR(mode):
  9. continue
  10. else:
  11. with open(subpath, "rb+") as file_handle:
  12. all_text = file_handle.read()
  13. if b"\r\n" in all_text:
  14. print("now is dos system convert to unix:",os.path.basename(subpath))
  15. elif b"\n" in all_text:
  16. print("now is unix system do nothing:",os.path.basename(subpath))
  17. all_change_text = all_text.replace(b"\r\n",b"\n")
  18. file_handle.seek(0, 0)
  19. file_handle.truncate()
  20. file_handle.write(all_change_text)
  21. def change_unix_to_dos(path):
  22. g = os.walk(path)
  23. files = ['%s/%s' % (i[0], j) for i in g for j in i[-1]]
  24. for subpath in files:
  25. mode = os.stat(subpath)[stat.ST_MODE]
  26. if stat.S_ISDIR(mode):
  27. continue
  28. else:
  29. with open(subpath, "rb+") as file_handle:
  30. all_text = file_handle.read()
  31. if b"\r\n" in all_text:
  32. print("now is dos system do nothing:",os.path.basename(subpath))
  33. elif b"\n" in all_text:
  34. print("now is unix system convert to dos:",os.path.basename(subpath))
  35. all_change_text = all_text.replace(b"\n", b"\r\n")
  36. file_handle.seek(0, 0)
  37. file_handle.truncate()
  38. file_handle.write(all_change_text)
  39. # print("change %s file to dos format." % subpath)
  40. if __name__ == '__main__':
  41. dir=r'F:\project\jushi\tensorrt-onnx-fasterrcnn-fpn-roialign-master\tensorrt_code\src\application\app_fasterrcnn_tmp'
  42. change_unix_to_dos(dir)

代码做了稍微改进,

原版:python文件格式(unix、windows)互换_Z小偉的博客-CSDN博客

相关文章