python小脚本-- tab符号转space符号

一段小脚本,用于将python文件中的tab转换为spaces,默认为一个1tab = 4 spaces.


# -*- coding: utf-8 -*-
"""
author:Robin Chan in lab313
usage: tab2space
a python script use to change tab to spaces
opts:
1--inputfilename
2--outputfilename
3--1/2 tab2space or space2tab
4--tabsize,means 1 tab = tabsize spaces
"""
#import getopt
import sys
def tab2spacefuc(inputfile,outputfile,tabsize):
    try:
       fp = open(inputfile,"r+")
       newfp = open(outputfile,"w")
    except Exception,info:
        print info
    inStr = '\t'
    outStr = tabsize*' '
    for eachline in fp.readlines():
        newStr = eachline.replace(inStr,outStr)
        newfp.write(newStr)
    fp.close()
    newfp.close()
    
def space2tabfuc(inputfile,outputfile,tabsize):
    try:
       fp = open(inputfile,"r+")
       newfp = open(outputfile,"w")
    except Exception,info:
        print info
    #inStr = tabsize*' '
    #outStr = '\t'
    num = 0
    for eachline in fp.readlines():
        i = 0
        while i < len(eachline)-1:
            i = i + 1
            if eachline[i] ==' ':
                num = num + 1
                if num == tabsize:
                    eachline[i-tabsize:i] = '\t'
            else:
                num = 0
        newStr = eachline
        newfp.write(newStr)
    fp.close()
    newfp.close()
    
if __name__ =="__main__":

    inputfile = sys.argv[1]#input file name
    outputfile = sys.argv[2]#output file name
    if len(sys.argv[1:]) < 3:#default set
        fuc = 1#tab2space
        tabsize = 4#default tabsize = 4,means 1 tab = 4 spaces
    else:
        fuc = sys.argv[3]#tab2space or space2tab
        tabsize = sys.argv[4]#tabsize
    if fuc == 1:
        tab2spacefuc(inputfile,outputfile,tabsize)
    else:
        space2tabfuc(inputfile,outputfile,tabsize)

        
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值