用Python实现换行符转换的脚本的教程

yipeiwu_com5年前Python基础

很简单的一个东西,在'\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 

相关文章

基于torch.where和布尔索引的速度比较

我就废话不多说了,直接上代码吧! import torch import time x = torch.Tensor([[1, 2, 3], [5, 5, 5], [7, 8, 9]...

在Python中等距取出一个数组其中n个数的实现方式

在Python中等距取出一个数组其中n个数的实现方式

应用场景: 实验中不断得到新数据,想将数据图形化,但随着时间推移,数据越来越多, 此时需要我们等距选择数据列表中固定数量的数据,来进行图形化。 注:保留首尾数据。 import nu...

python求最大值最小值方法总结

python求最大值最小值方法总结

方法一(常规): 代码: count = int(input('输入数据个数:\n')) a = 1 while a <= count: num = int(input(...

使用Python中的reduce()函数求积的实例

使用Python中的reduce()函数求积的实例

编写一个prod()函数,可以接受一个list并利用reduce()求积。 from functools import reduce def prod(x,y): return x...

解决Python中list里的中文输出到html模板里的问题

最仅在做一个数据分析的功能时候遇到将list中的中文字符按照数组的形式输出到html模板里的js中进行处理,但是直接输出模板会按照unicode编码输出,这个问题真的让人头大。 本方法实...