ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Tabify
Submitter: Yuce Tekol (other recipes)
Last Updated: 2006/07/19
Version no: 1.2
Category: Programs

 

Not Rated yet


Description:

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

Source: Text Source

#!/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()

Discussion:

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.



Add comment

Number of comments: 1

Well, tabify this :), Christos Georgiou, 2006/10/03

__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.
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.