用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获取脚本所在目录的正确方法
Apr 15 Python
python中实现定制类的特殊方法总结
Sep 28 Python
深入讲解Python中的迭代器和生成器
Oct 26 Python
python线程、进程和协程详解
Jul 19 Python
python对DICOM图像的读取方法详解
Jul 17 Python
python输出100以内的质数与合数实例代码
Jul 08 Python
Ubuntu18.04中Python2.7与Python3.6环境切换
Jun 14 Python
Python socket 套接字实现通信详解
Aug 27 Python
Python使用Opencv实现图像特征检测与匹配的方法
Oct 30 Python
Python通过Tesseract库实现文字识别
Mar 05 Python
pycharm中leetcode插件使用图文详解
Dec 07 Python
python网络爬虫实现发送短信验证码的方法
Feb 25 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
PHP的ASP防火墙
2006/10/09 PHP
smarty自定义函数用法示例
2016/05/20 PHP
Js+XML 操作
2006/09/20 Javascript
用JavaScript实现单继承和多继承的简单方法
2009/03/29 Javascript
Lazy Load 延迟加载图片的 jQuery 插件
2010/02/06 Javascript
jquery ajax执行后台方法
2010/03/18 Javascript
jquery ajax实现下拉框三级无刷新联动,且保存保持选中值状态
2013/10/29 Javascript
详解JS 比较两个Json对象的值是否相等的实例
2013/11/20 Javascript
Javascript原型链和原型的一个误区
2014/10/22 Javascript
JS动画效果打开、关闭层的实现方法
2015/05/09 Javascript
完美实现bootstrap分页查询
2015/12/09 Javascript
JavaScript+CSS实现的可折叠二级菜单实例
2016/02/29 Javascript
如何清除IE10+ input X 文本框的叉叉和密码输入框的眼睛图标
2016/12/21 Javascript
使用D3.js构建实时图形的示例代码
2018/08/28 Javascript
JS中实现一个下载进度条及播放进度条的代码
2019/06/10 Javascript
jquery中为什么能用$操作
2019/06/18 jQuery
区分vue-router的hash和history模式
2020/10/03 Javascript
[07:40]DOTA2每周TOP10 精彩击杀集锦vol.4
2014/06/25 DOTA
深入理解NumPy简明教程---数组1
2016/12/17 Python
Python正则表达式实现截取成对括号的方法
2017/01/06 Python
python WindowsError的错误代码详解
2017/07/23 Python
pandas创建新Dataframe并添加多行的实例
2018/04/08 Python
PyCharm安装第三方库如Requests的图文教程
2018/05/18 Python
python生成随机红包的实例写法
2019/09/02 Python
pytorch之Resize()函数具体使用详解
2020/02/27 Python
Selenium 滚动页面至元素可见的方法
2020/03/18 Python
浅谈Python里面None True False之间的区别
2020/07/09 Python
中国梦的演讲稿
2014/01/08 职场文书
学生社团文化节开幕式主持词
2014/03/28 职场文书
影视后期实训报告
2014/11/05 职场文书
长城导游词400字
2015/01/30 职场文书
车间班组长竞聘书
2015/09/15 职场文书
八年级作文之一起的走过日子
2019/09/17 职场文书
创业计划书之电动车企业
2019/10/11 职场文书
详解Python常用的魔法方法
2021/06/03 Python
Python实现自动玩连连看的脚本分享
2022/04/04 Python