Python script to convert tab characters to spaces
- August 24th, 2010
- Posted in Uncategorized
- By jrod
- Write comment
(kickstart)jared@eve:~/kickstart/debian_post/trunk$ cat /home/jared/tab2space.py
import sys
import os
import shutil
from tempfile import mkstemp
DEBUG = True
tab = '\x09'
space = '\x20'
expand = space * 4
score = [0, 0]
if len(sys.argv) < 2:
print 'File path argument required.'
sys.exit(-1)
path = sys.argv[1]
old_fp = open(path, 'r')
temp_fd, temp_path = mkstemp()
temp_fp = open(temp_path, 'w')
for line in old_fp:
if DEBUG:
if line.find(tab) > -1:
print 'tab character found on line ' + str(score[0] + 1)
score[1] = score[1] + 1
temp_fp.write(line.replace(tab, expand))
score[0] = score[0] + 1
if DEBUG:
print 'total lines using the tab character: ' + str(score[1])
temp_fp.close()
old_fp.close()
bak_file = path + '.tab2space'
shutil.move(path, bak_file)
shutil.move(temp_path, path)
os.chmod(path, 0644)
Yes.. I know that expand does this already. Just wanted to show a python implementation. After all, it is python that makes the expand command mission critical and not mere aesthetics.
Also.. stop using tabs people. #{SearchEngine} ‘vim expandtab’