用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 相关文章推荐
Djang中静态文件配置方法
Jul 30 Python
老生常谈Python startswith()函数与endswith函数
Sep 08 Python
python操作mysql代码总结
Jun 01 Python
Python之list对应元素求和的方法
Jun 28 Python
python 字典中文key处理,读取,比较方法
Jul 06 Python
Python中作用域的深入讲解
Dec 10 Python
TensorFlow tf.nn.max_pool实现池化操作方式
Jan 04 Python
新年福利来一波之Python轻松集齐五福(demo)
Jan 20 Python
动态设置django的model field的默认值操作步骤
Mar 30 Python
python将数据插入数据库的代码分享
Aug 16 Python
python判断变量是否为列表的方法
Sep 17 Python
python tqdm用法及实例详解
Jun 16 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类
2006/07/15 PHP
php数据入库前清理 注意php intval与mysql的int取值范围不同
2010/12/12 PHP
PHP实现文件下载【实例分享】
2017/04/28 PHP
Laravel5.1框架注册中间件的三种场景详解
2019/07/09 PHP
获得Javascript对象属性个数的示例代码
2013/11/21 Javascript
Javascript 按位左移运算符使用介绍(
2014/02/04 Javascript
浅谈js里面的InttoStr和StrtoInt
2016/06/14 Javascript
微信小程序实现缓存根据不同的id来进行设置和读取缓存
2017/06/12 Javascript
Vue中封装input组件的实例详解
2017/10/17 Javascript
JS实现图片放大镜插件详解
2017/11/06 Javascript
基于vue2.0实现简单轮播图
2017/11/27 Javascript
使用Node搭建reactSSR服务端渲染架构
2018/08/30 Javascript
vue项目在安卓低版本机显示空白的原因分析(两种)
2018/09/04 Javascript
详解基于Vue/React项目的移动端适配方案
2019/08/23 Javascript
基于jquery实现彩色投票进度条代码解析
2020/08/26 jQuery
python中的装饰器详解
2015/04/13 Python
python+Django+apache的配置方法详解
2016/06/01 Python
Python中selenium实现文件上传所有方法整理总结
2017/04/01 Python
利用python打印出菱形、三角形以及矩形的方法实例
2017/08/08 Python
python 保存float类型的小数的位数方法
2018/10/17 Python
浅谈python连续赋值可能引发的错误
2018/11/10 Python
Window环境下Scrapy开发环境搭建
2018/11/18 Python
使用Python 统计高频字数的方法
2019/01/31 Python
Python threading的使用方法解析
2019/08/28 Python
python科学计算之narray对象用法
2019/11/25 Python
Python创建空列表的字典2种方法详解
2020/02/13 Python
css3实现顶部社会化分享按钮示例
2014/05/06 HTML / CSS
HTML5 新旧语法标记对我们有什么好处
2012/12/13 HTML / CSS
美国巧克力喷泉品牌:Sephra
2019/05/05 全球购物
欧洲最大的高尔夫零售商:American Golf
2019/09/02 全球购物
自我评价如何写好?
2014/01/05 职场文书
药学专业学生的自我评价分享
2014/02/06 职场文书
志愿者活动总结报告
2014/06/27 职场文书
优秀班主任先进事迹材料
2014/12/16 职场文书
一文搞懂Redis中String数据类型
2022/04/03 Redis
电脑开机弹出documents文件夹怎么回事?弹出documents文件夹解决方法
2022/04/08 数码科技