用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 

相关文章

Pycharm更换python解释器的方法

安装了pycharm之后有一个新装的python解释器,顶替了之前系统的python 那样的话,原来利用pip安装的一些库会无法import. 要么加入环境变量,要么更换运行的解释器:...

Python使用APScheduler实现定时任务过程解析

Python使用APScheduler实现定时任务过程解析

前言 APScheduler是基于Quartz的一个Python定时任务框架。提供了基于日期、固定时间间隔以及crontab类型的任务,并且可以持久化任务。 在线文档:https://...

python中文乱码的解决方法

乱码原因: 源码文件的编码格式为utf-8,但是window的本地默认编码是gbk,所以在控制台直接打印utf-8的字符串当然是乱码了! 解决方法: 1、print mystr.deco...

详解用python写一个抽奖程序

第一次使用python写程序,确实比C/C++之类方便许多。既然这个抽奖的数据不大,对效率要求并不高,所以采用python写,更加简洁、清晰、方便。 1.用到的模块 生成随机数的模...

Python变量、数据类型、数据类型转换相关函数用法实例详解

Python变量、数据类型、数据类型转换相关函数用法实例详解

本文实例讲述了Python变量、数据类型、数据类型转换相关函数用法。分享给大家供大家参考,具体如下: python变量的使用不需要进行类型声明(类型名 变量名),给一个变量名赋什么值就是...