用Python实现换行符转换的脚本的教程

 更新时间:2015年04月16日 09:12:15   作者:dbzhang800  
这篇文章主要介绍了用Python实现换行符转换的脚本的教程,代码非常简单,包括一个对操作说明的功能的实现,需要的朋友可以参考下

很简单的一个东西,在'\n'、'\r\n'、'\r'3中换行符之间进行转换。
用法

复制代码 代码如下:
usage: eol_convert.py [-h] [-r] [-m {u,p,w,m,d}] [-k] [-f]
                      filename [filename ...]

Convert Line Ending

positional arguments:
  filename        file names

optional arguments:
  -h, --help      show this help message and exit
  -r              walk through directory
  -m {u,p,w,m,d}  mode of the line ending
  -k              keep output file date
  -f              force conversion of binary files

源码

这只能算是argparse模块和os模块的utime()、stat()、walk()的一个简单的练习。可以用,但还相当不完善。

 #!/usr/bin/env python 
  #2009-2011 dbzhang800 
  import os 
  import re 
  import os.path 
   
  def convert_line_endings(temp, mode): 
    if mode in ['u', 'p']: #unix, posix 
      temp = temp.replace('\r\n', '\n') 
      temp = temp.replace('\r', '\n') 
    elif mode == 'm':   #mac (before Mac OS 9) 
      temp = temp.replace('\r\n', '\r') 
      temp = temp.replace('\n', '\r') 
    elif mode == 'w':   #windows 
      temp = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", temp) 
    return temp 
   
  def convert_file(filename, args): 
    statinfo = None 
    with file(filename, 'rb+') as f: 
      data = f.read() 
      if '\0' in data and not args.force: #skip binary file... ? 
        print '%s is a binary file?, skip...' % filename 
        return 
      newdata = convert_line_endings(data, args.mode) 
      if (data != newdata): 
        statinfo = os.stat(filename) if args.keepdate else None 
        f.seek(0) 
        f.write(newdata) 
        f.truncate() 
    if statinfo: 
      os.utime(filename, (statinfo.st_atime, statinfo.st_mtime)) 
    print filename 
   
  def walk_dir(d, args): 
    for root, dirs, files in os.walk(d): 
      for name in files: 
        convert_file(os.path.join(root, name), args) 
   
  if __name__ == '__main__': 
    import argparse 
    import sys 
    parser = argparse.ArgumentParser(description='Convert Line Ending') 
    parser.add_argument('filename', nargs='+', help='file names') 
    parser.add_argument('-r', dest='recursive', action='store_true', 
        help='walk through directory') 
    parser.add_argument('-m', dest='mode', default='d', choices='upwmd', 
        help='mode of the line ending') 
    parser.add_argument('-k', dest='keepdate', action='store_true', 
        help='keep output file date') 
    parser.add_argument('-f', dest='force', action='store_true', 
        help='force conversion of binary files') 
    args = parser.parse_args() 
    if args.mode == 'd': 
      args.mode = 'w' if sys.platform == 'win32' else 'p' 
   
    for filename in args.filename: 
      if os.path.isdir(filename): 
        if args.recursive: 
          walk_dir(filename, args) 
        else: 
          print '%s is a directory, skip...' % filename 
      elif os.path.exists(filename): 
        convert_file(filename, args) 
      else: 
        print '%s does not exist' % filename 

相关文章

  • python实现切割url得到域名、协议、主机名等各个字段的例子

    python实现切割url得到域名、协议、主机名等各个字段的例子

    今天小编就为大家分享一篇python实现切割url得到域名、协议、主机名等各个字段的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-07-07
  • matplotlib基本图形绘制操作实例

    matplotlib基本图形绘制操作实例

    这篇文章主要为大家介绍了matplotlib基本图形绘制操作实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • python出现RuntimeError错误问题及解决

    python出现RuntimeError错误问题及解决

    这篇文章主要介绍了python出现RuntimeError错误问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • Python机器学习库sklearn(scikit-learn)的基础知识和高级用法

    Python机器学习库sklearn(scikit-learn)的基础知识和高级用法

    Scikit-Learn是 Python 最流行的机器学习库之一,它提供了各种工具来实现、评估和探索各种学习算法,用于,各种机器学习任务,在本教程中,我们将介绍 Scikit-Learn 的基础知识和一些高级用法,并提供一些实例代码来帮助我们更好地理解
    2023-07-07
  • numpy删除单行、删除单列、删除多列实现方式

    numpy删除单行、删除单列、删除多列实现方式

    这篇文章主要介绍了numpy删除单行、删除单列、删除多列实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-02-02
  • Python3按一定数据位数格式处理bin文件的方法

    Python3按一定数据位数格式处理bin文件的方法

    今天小编就为大家分享一篇Python3按一定数据位数格式处理bin文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python导入不同文件夹中文件的方法详解

    Python导入不同文件夹中文件的方法详解

    在写python程序的时候,经常会用到引入其他文件夹里的py文件,下面这篇文章主要给大家介绍了关于Python导入不同文件夹中文件的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-06-06
  • python的id()函数解密过程

    python的id()函数解密过程

    id()函数在使用过程中很频繁,为此本人对此函数深入研究下,晒出代码和大家分享下,希望对你们有所帮助
    2012-12-12
  • Python中数组遍历的方法总结

    Python中数组遍历的方法总结

    数组是编程中经常使用的数据结构,用于存储和操作一组元素,Python提供了多种方法来遍历数组,本文将深入探讨这些方法,提供详细的示例代码,希望对大家有所帮助
    2023-11-11
  • python读取文本中的坐标方法

    python读取文本中的坐标方法

    今天小编就为大家分享一篇python读取文本中的坐标方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10

最新评论