Welcome, guest | Sign In | My Account | Store | Cart

A little script for those of us who prefer tabs over spaces.

Python, 50 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/python
# tabify.py -- Convert indentation with spaces to tabs
# 2006-01-23 by Yuce Tekol. www.geocities.com/yucetekol
# Last modification: 2006-07-18

import sys
import os
from stat import ST_MODE
import tokenize

__VERSION__ = "0.5.1"

def tabify(filename):
	mode = os.stat(filename)[ST_MODE]
	os.rename(filename, filename+".bak")
	
	infile = file(filename+".bak")
	outfile = file(filename,"w")
	tokens = tokenize.generate_tokens(infile.readline)
		
	text = []
	indent = 0
	minlineno = 0
	for (toktype, token, start, end, line) in tokens:
		y, x = end
		
		if toktype == tokenize.INDENT:
			indent += 1
		elif toktype == tokenize.DEDENT:
			indent -= 1
		elif y > minlineno:
			minlineno = y
			text += "%s%s\n" % ("\t"*indent,line.strip())
			
	outfile.write("".join(text))
	
	infile.close()
	outfile.close()
	os.chmod(filename, mode)

def main():
	if len(sys.argv) < 2:
		print "usage: %s file1.py file2.py ..." % sys.argv[0]
		sys.exit()
			
	for filename in sys.argv[1:]:
		tabify(filename)
	
if __name__ == "__main__":
	main()

Since I always use tabs to indent, it becomes a pain to modify Python source files from others who use spaces. Python includes a small script to untabify to convert tab indented source code to spaced one, but no utility the other way around; I hope this little script will fill that gap.

You can use this script by supplying the names of the files in the command line (e.g): $ python tabify hello.py world.py

The script creates backups of the original files, by adding .bak to their filenames.

1 comment

Christos Georgiou 17 years, 6 months ago  # | flag

Well, tabify this :).

__doc__ = """
    This is module-level documentation
"""

You will notice that triple-quotes and newlines don't mix well in your code. Also, from stat import ST_MODE is unnecessary for a long time now. os.stat(filename).st_mode is more practical.