python unix、windows 文件格式互换

举报
风吹稻花香 发表于 2022/08/06 23:09:34 2022/08/06
【摘要】 import osimport stat def change_dos_to_unix(path): g = os.walk(path) files = ['%s/%s' % (i[0], j) for i in g for j in i[-1]] for subpath in files: mo...


  
  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博客

文章来源: blog.csdn.net,作者:AI视觉网奇,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/jacke121/article/details/126190773

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。