用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 相关文章推荐
linux下python抓屏实现方法
May 22 Python
基python实现多线程网页爬虫
Sep 06 Python
利用Python批量生成任意尺寸的图片
Aug 29 Python
DataFrame中的object转换成float的方法
Apr 10 Python
python3+PyQt5实现文档打印功能
Apr 24 Python
pandas 小数位数 精度的处理方法
Jun 09 Python
在Python 不同级目录之间模块的调用方法
Jan 19 Python
Pandas之Fillna填充缺失数据的方法
Jun 25 Python
深入学习python多线程与GIL
Aug 26 Python
Python 生成器,迭代,yield关键字,send()传参给yield语句操作示例
Oct 12 Python
python 正则表达式参数替换实例详解
Jan 17 Python
Python利用folium实现地图可视化
May 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 mysql数据库操作分页类
2008/06/04 PHP
深入PHP购物车模块功能分析(函数讲解,附源码)
2013/06/25 PHP
PHP代码优化的53个细节
2014/03/03 PHP
php的ZipArchive类用法实例
2014/10/20 PHP
php中删除数组的第一个元素和最后一个元素的函数
2015/03/07 PHP
使用jQuery判断IE浏览器版本的代码
2014/06/14 Javascript
javascript 获取函数形参个数
2014/07/31 Javascript
Javascript中setTimeOut和setInterval的定时器用法
2015/06/12 Javascript
尝试动手制作javascript放大镜效果
2015/12/25 Javascript
实用jquery操作表单元素的简单代码
2016/07/04 Javascript
chosen实现省市区三级联动
2018/08/16 Javascript
微信小程序 JS动态修改样式的实现方法
2018/12/16 Javascript
Vue自定义render统一项目组弹框功能
2020/06/07 Javascript
在react-antd中弹出层form内容传递给父组件的操作
2020/10/24 Javascript
ES6 十大特性简介
2020/12/09 Javascript
Python中的二叉树查找算法模块使用指南
2014/07/04 Python
给Python IDLE加上自动补全和历史功能
2014/11/30 Python
关于pip的安装,更新,卸载模块以及使用方法(详解)
2017/05/19 Python
python与sqlite3实现解密chrome cookie实例代码
2018/01/20 Python
Python使用re模块正则提取字符串中括号内的内容示例
2018/06/01 Python
python日志模块logbook使用方法
2019/09/19 Python
如何使用python进行pdf文件分割
2019/11/11 Python
解决python 找不到module的问题
2020/02/12 Python
python ssh 执行shell命令的示例
2020/09/29 Python
Python+OpenCV图像处理—— 色彩空间转换
2020/10/22 Python
HTML5 Blob对象的具体使用
2020/05/22 HTML / CSS
美国知名的摄影器材销售网站:Adorama
2017/02/01 全球购物
联想香港官方网站及网店:Lenovo香港
2018/04/13 全球购物
我的画教学反思
2014/04/28 职场文书
代理人委托书
2014/08/01 职场文书
美德少年事迹材料1000字
2014/08/21 职场文书
2014年群众路线党员自我评议
2014/09/24 职场文书
2015年民主生活会发言材料
2014/12/15 职场文书
幼儿园小班教师个人工作总结
2015/02/06 职场文书
Python使用OpenCV实现虚拟缩放效果
2022/02/28 Python
Java 轮询锁使用时遇到问题
2022/05/11 Java/Android