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


Posted in Python onApril 16, 2015

很简单的一个东西,在'\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调用C语言的方法【基于ctypes模块】
Jan 22 Python
python分治法求二维数组局部峰值方法
Apr 03 Python
Python Flask前后端Ajax交互的方法示例
Jul 31 Python
python中多个装饰器的执行顺序详解
Oct 08 Python
python实时检测键盘输入函数的示例
Jul 17 Python
python 实现矩阵填充0的例子
Nov 29 Python
Python操作Excel把数据分给sheet
May 20 Python
深入了解python列表(LIST)
Jun 08 Python
详解pyinstaller生成exe的闪退问题解决方案
Jun 19 Python
python中tkinter窗口位置\坐标\大小等实现示例
Jul 09 Python
详解Python requests模块
Jun 21 Python
Python学习之os包使用教程详解
Mar 21 Python
Python下的subprocess模块的入门指引
Apr 16 #Python
Python下的twisted框架入门指引
Apr 15 #Python
Python代码调试的几种方法总结
Apr 15 #Python
详解Python中with语句的用法
Apr 15 #Python
python获取本机外网ip的方法
Apr 15 #Python
python中常用检测字符串相关函数汇总
Apr 15 #Python
python使用自定义user-agent抓取网页的方法
Apr 15 #Python
You might like
laravel中Redis队列监听中断的分析
2020/09/14 PHP
理解Javascript_13_执行模型详解
2010/10/20 Javascript
JQuery.ajax传递中文参数的解决方法 推荐
2011/03/28 Javascript
页面载入结束自动调用js函数示例
2013/09/23 Javascript
js判断为空Null与字符串为空简写方法
2014/02/24 Javascript
jquery预加载图片的方法
2015/05/27 Javascript
apply和call方法定义及apply和call方法的区别
2015/11/15 Javascript
canvas实现粒子时钟效果
2017/02/06 Javascript
js编写简单的计时器功能
2017/07/15 Javascript
详解vue 项目白屏解决方案
2018/10/31 Javascript
Angular6 发送手机验证码按钮倒计时效果实现方法
2019/01/08 Javascript
一篇文章介绍redux、react-redux、redux-saga总结
2019/05/23 Javascript
vue setInterval 定时器失效的解决方式
2020/07/30 Javascript
vue watch监控对象的简单方法示例
2021/01/07 Vue.js
python数字图像处理之高级滤波代码详解
2017/11/23 Python
对python的输出和输出格式详解
2018/12/08 Python
python实现连续图文识别
2018/12/18 Python
详解python和matlab的优势与区别
2019/06/28 Python
python机器学习包mlxtend的安装和配置详解
2019/08/21 Python
git查看、创建、删除、本地、远程分支方法详解
2020/02/18 Python
Django DRF认证组件流程实现原理详解
2020/08/17 Python
python利用线程实现多任务
2020/09/18 Python
Python实现EM算法实例代码
2020/10/04 Python
HTML5实现表单自动验证功能实例代码
2017/01/11 HTML / CSS
伊利莎白雅顿官网:Elizabeth Arden
2016/10/10 全球购物
SEPHORA新西兰官方网站:购买化妆品和护肤品
2016/12/02 全球购物
美国大码时尚女装购物网站:ELOQUII
2017/12/28 全球购物
台湾菁英交友:结识黄金单身的台湾人
2018/01/22 全球购物
Java方面的关于数组和继承的笔面试题
2015/09/18 面试题
个人简历自我评价
2014/02/02 职场文书
应届生找工作求职信
2014/06/24 职场文书
学生会竞选演讲稿纪检部
2014/08/25 职场文书
弘扬焦裕禄精神践行三严三实心得体会
2014/10/13 职场文书
行政人事专员岗位职责
2015/04/07 职场文书
大学副班长竞选稿
2015/11/21 职场文书
子女赡养老人协议书
2016/03/23 职场文书