经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » UNIX » 查看文章
使用python实现unix2dos和dos2unix命令的例子
来源:jb51  时间:2019/8/14 8:42:35  对本文有异议

由于工作电脑网络限制无法安装unix2dos和dos2unix命令转换文件,自己实现一个

直接上代码,保存为python文件如unix2dos.py然后使用命令

  1. unix2dos.py {unix2dos|dos2unix} {dirname|filename}
  1. #! /usr/bin/env python
  2. # coding=utf-8
  3. import os
  4. import sys
  5. try:
  6. input = raw_input
  7. except:
  8. pass
  9. def usage():
  10. print('Usage:')
  11. print('\t %s' % ('unix2dos.py {unix2dos|dos2unix} {dirname|filename}'))
  12. def err_exit(msg):
  13. if msg: print('%s' % msg)
  14. usage()
  15. sys.exit(0)
  16. def getfiles(root):
  17. for dirpath, dirnames, filenames in os.walk(root):
  18. for filename in filenames:
  19. yield os.path.join(dirpath, filename)
  20. def format_file(file, toformat='unix2dos'):
  21. print('Formatting %s:\t%s' % (toformat, file))
  22. if not os.path.isfile(file):
  23. print('ERROR: %s invalid normal file' % file)
  24. return
  25. if toformat == 'unix2dos':
  26. line_sep = '\r\n'
  27. else:
  28. line_sep = '\n'
  29. with open(file, 'r') as fd:
  30. tmpfile = open(file+toformat, 'w+b')
  31. for line in fd:
  32. line = line.replace('\r', '')
  33. line = line.replace('\n', '')
  34. tmpfile.write(line+line_sep)
  35. tmpfile.close()
  36. os.rename(file+toformat, file)
  37. def uni_format_proc(filename, toformat):
  38. if not toformat or toformat not in ['unix2dos', 'dos2unix']:
  39. err_exit('ERROR: %s: Invalid format param' % (toformat))
  40. if not filename or not os.path.exists(filename):
  41. err_exit('ERROR: %s: No such file or directory' % (filename))
  42. if os.path.isfile(filename):
  43. format_file(filename, toformat)
  44. return
  45. if os.path.isdir(filename):
  46. for file in getfiles(filename):
  47. uni_format_proc(file, toformat)
  48. if __name__ == '__main__':
  49. if len(sys.argv) != 3:
  50. err_exit('ERROR: Invalid arguments')
  51. uni_format_proc(filename=sys.argv[2], toformat=sys.argv[1])

以上这篇使用python实现unix2dos和dos2unix命令的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号