首先我遇到的一个问题是,我明明在.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'
欢迎大家提出更好的解决方法,我也是新手。这是我写的第一个实用脚本文件。