用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中的rjust()方法使用详解
May 19 Python
python实现单线程多任务非阻塞TCP服务端
Jun 13 Python
Python模拟随机游走图形效果示例
Feb 06 Python
python 实现对文件夹内的文件排序编号
Apr 12 Python
python 读取鼠标点击坐标的实例
Dec 29 Python
实例讲解Python中浮点型的基本内容
Feb 11 Python
python循环定时中断执行某一段程序的实例
Jun 29 Python
django的auth认证,authenticate和装饰器功能详解
Jul 25 Python
python tkinter基本属性详解
Sep 16 Python
使用tensorflow框架在Colab上跑通猫狗识别代码
Apr 26 Python
Python 如何操作 SQLite 数据库
Aug 17 Python
python 实现的截屏工具
May 08 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
wiki-shan写的php在线加密的解密程序
2008/09/07 PHP
深入array multisort排序原理的详解
2013/06/18 PHP
为百度UE编辑器上传图片添加水印功能
2015/04/16 PHP
PHP PDOStatement::execute讲解
2019/01/31 PHP
关于IE BUG与字符串截取substr的解决办法
2013/04/10 Javascript
SuperSlide2实现图片滚动特效
2014/06/20 Javascript
JavaScript实现的使用键盘控制人物走动实例
2014/08/27 Javascript
jquery实现适用于门户站的导航下拉菜单效果代码
2015/08/24 Javascript
基于cssSlidy.js插件实现响应式手机图片轮播效果
2016/08/30 Javascript
如何使用Vuex+Vue.js构建单页应用
2016/10/27 Javascript
Angular实现跨域(搜索框的下拉列表)
2017/02/16 Javascript
JavaScript之DOM插入更新删除_动力节点Java学院整理
2017/07/03 Javascript
JavaScript模拟文件拖选框样式v1.0的实例
2017/08/04 Javascript
帝国cms首页列表页实现点赞功能
2017/10/30 Javascript
JavaScript计算正方形面积
2019/11/26 Javascript
微信小程序开发(一):服务器获取数据列表渲染操作示例
2020/06/01 Javascript
JavaScript中layim之整合右键菜单的示例代码
2021/02/06 Javascript
python3.3教程之模拟百度登陆代码分享
2014/01/16 Python
Python实现多进程的四种方式
2019/02/22 Python
python文本数据处理学习笔记详解
2019/06/17 Python
对pyqt5中QTabWidget的相关操作详解
2019/06/21 Python
python rsync服务器之间文件夹同步脚本
2019/08/29 Python
Python笔记之观察者模式
2019/11/20 Python
python如何运行js语句
2020/09/09 Python
python爬虫爬取图片的简单代码
2021/01/18 Python
浅谈CSS3动画的回调处理
2016/07/21 HTML / CSS
Conforama瑞士:家具、厨房、电器、装饰
2020/09/06 全球购物
力学专业毕业生自荐信
2013/11/17 职场文书
村党支部换届选举方案
2014/05/02 职场文书
经营理念标语
2014/06/21 职场文书
经济贸易系求职信
2014/08/04 职场文书
结对共建协议书
2014/08/20 职场文书
做一个有道德的人活动方案
2014/08/25 职场文书
卡特教练观后感
2015/06/08 职场文书
公司员工管理制度
2015/08/04 职场文书
动画电影《擅长捉弄人的高木同学》6月10日上映!
2022/03/20 日漫