把python脚本文件的自动换行数(indent width )变为4 的一个脚本

首先我遇到的一个问题是,我明明在.exrc中设置 tabstop=4。但不知怎么的,文件里tab的空格数就是不对。

现在把这些不对的tab转换为正确的tab,即4空格/tap。

下面是文件(注,不适用对于用空格来缩进的文件):

import sys

if len(sys.argv)<=1:
    print '%s arg1 [arg2 ..]' % __file__
    sys.exit(1)

files=sys.argv[1:]
spaces='    '
for f in files:
    try:
        fd=open(f,'r')
        fd1=open(f+'.new','w')
    except Exception, e:
        print 'Error',e
        sys.exit(1)
    tab_count_prev=0
    tab_count_cur=0
    tabs=0
    for line in fd.readlines():
        tab_count_cur=line.count('\t')
        if tab_count_cur==0:
            tabs=0
        elif tab_count_prev==0:
            tabs+=1    
        elif tab_count_cur==tab_count_prev:
            pass
        elif tab_count_cur > tab_count_prev:
            tabs+=1
        elif tab_count_cur < tab_count_prev:
            tabs-=1
            
        tab_count_prev=tab_count_cur
        fd1.write(spaces * tabs + line.lstrip('\t'))
    fd.close()
    fd1.close()

print 'process successfully'
    

欢迎大家提出更好的解决方法,我也是新手。这是我写的第一个实用脚本文件。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值