用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 23 Python
Python实现栈的方法
May 26 Python
python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)
Mar 12 Python
Python3 导入上级目录中的模块实例
Feb 16 Python
python代理工具mitmproxy使用指南
Jul 04 Python
Python OpenCV 使用滑动条来调整函数参数的方法
Jul 08 Python
python tkinter组件使用详解
Sep 16 Python
python用Tkinter做自己的中文代码编辑器
Sep 07 Python
通过代码简单了解django model序列化作用
Nov 12 Python
Python图片验证码降噪和8邻域降噪
Aug 30 Python
Python用any()函数检查字符串中的字母以及如何使用all()函数
Apr 14 Python
利用Python脚本写端口扫描器socket,python-nmap
Jul 23 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中header和session_start前不能有输出原因分析
2013/01/11 PHP
PHP向socket服务器收发数据的方法
2015/01/24 PHP
php实现无限级分类查询(递归、非递归)
2016/03/10 PHP
PHP预定义变量9大超全局数组用法详解
2016/04/23 PHP
php mysql_real_escape_string addslashes及mysql绑定参数防SQL注入攻击
2016/12/23 PHP
thinkPHP5框架自定义验证器实现方法分析
2018/06/11 PHP
js传值 判断
2006/10/26 Javascript
JavaScript实用技巧(一)
2010/08/16 Javascript
window.event快达到全浏览器支持了,以后使用就方便了
2011/11/30 Javascript
iframe的onreadystatechange事件在firefox下的使用
2014/04/16 Javascript
原生javascript实现图片滚动、延时加载功能
2015/01/12 Javascript
Javascrip实现文字跳动特效
2016/11/27 Javascript
Nodejs 发送Post请求功能(发短信验证码例子)
2017/02/09 NodeJs
jQuery文字轮播特效
2017/02/12 Javascript
JavaScript登录记住密码操作(超简单代码)
2017/03/22 Javascript
Vue学习笔记进阶篇之单元素过度
2017/07/19 Javascript
AngularJS实现的根据数量与单价计算总价功能示例
2017/12/26 Javascript
vue-cli项目中使用公用的提示弹层tips或加载loading组件实例详解
2018/05/28 Javascript
vue2 v-model/v-text 中使用过滤器的方法示例
2019/05/09 Javascript
微信小程序自定义可滑动顶部TabBar选项卡实现页面切换功能示例
2019/05/14 Javascript
小程序多图列表实现性能优化的方法步骤
2019/05/28 Javascript
Python实现的计数排序算法示例
2017/11/29 Python
python 3调用百度OCR API实现剪贴板文字识别
2018/09/04 Python
python实现淘宝秒杀脚本
2020/06/23 Python
Django给admin添加Action的步骤详解
2019/05/01 Python
html5视频播放_动力节点Java学院整理
2017/07/13 HTML / CSS
WWE美国职业摔角官方商店:WWE Shop
2018/11/15 全球购物
命名空间(namespace)和程序集(Assembly)有什么区别
2015/09/25 面试题
培训演讲稿范文
2014/01/12 职场文书
捐款倡议书范文
2014/02/02 职场文书
中学校庆方案
2014/03/17 职场文书
2015年市场营销工作总结
2015/07/23 职场文书
小学三年级数学教学反思
2016/02/16 职场文书
2016年推广普通话宣传周活动总结
2016/04/06 职场文书
2019自荐信范文集锦!
2019/07/03 职场文书
利用ajax+php实现商品价格计算
2021/03/31 PHP