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

yipeiwu_com5年前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对数据进行插值和下采样的方法

使用Python进行插值非常方便,可以直接使用scipy中的interpolate import numpy as np x1 = np.linspace(1, 4096, 1024...

轻松理解Python 中的 descriptor

定义 通常,一个 descriptor 是具有“绑定行为”的对象属性。所绑定行为可通过 descriptor 协议被自定义的 __get__() , __set__() 和 __dele...

在Python中将函数作为另一个函数的参数传入并调用的方法

在Python中,函数本身也是对象,所以可以将函数作为参数传入另一函数并进行调用 在旧版本中,可以使用apply(function, *args, **kwargs)进行调用,但是在新版...

对Python 两大环境管理神器 pyenv 和 virtualenv详解

简介 pyenv 是一个开源的 Python 版本管理工具,可以轻松地给系统安装任意 Python 版本,想玩哪个版本,瞬间就可以切换。有了 pyenv,我们不需要再为系统多版本 Pyt...

python实现12306登录并保存cookie的方法示例

经过倒腾12306的登录,还是实现了,请求头很重要...各位感兴趣的可以继续写下去..... import sys import time import requests from...