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: expand_tabs.py - expand tabs in files in-place
Submitter: Ori Peleg (other recipes)
Last Updated: 2006/10/07
Version no: 1.1
Category: Programs

 

Not Rated yet


Description:

expand_tabs.py - Similar to Unix's expand(1) command, but can edit the files in-place.

Source: Text Source

#!/usr/bin/env python
import fileinput, optparse, sys

# Command-line parser
parser = optparse.OptionParser(
        usage="""
%prog [options] [files]
Expand tab to spaces, printing to the standard output by default.
When no files are given, read from the standard input.

Examples:
 expand in one file
    % expand_tabs.py -t 4 file.txt

 expand tabs in Python source files
    % find . -name "*.py" | xargs expand_tabs.py -it 4
""".strip(),
        formatter=optparse.IndentedHelpFormatter(max_help_position=30)
    )
parser.add_option("-t", "--tabsize", type="int", metavar="SIZE")
parser.add_option("-i", "--inplace", action="store_true", help="change the files in-place (don't print)")
parser.add_option("-b", "--backupext", default="", metavar="EXT", help="backup extension to use (default: no backup)")

options, args = parser.parse_args()
if options.tabsize is None:
    parser.error("tab size not specified")

# Do the work
for line in fileinput.input(files=args, inplace=options.inplace, backup=options.backupext):
    sys.stdout.write( line.expandtabs(options.tabsize) )

Discussion:

Sadly, expand(1) doesn't support in-line replacement, so this is a humble alternative.

The option parsing takes most of the code because this is meant as an actual utility, but all the real work is in module 'fileinput' and the 'expandtabs' string method.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Treat the Win32 Registry ...

5. a friendly mkdir()

6. Wrapping template engine ...

7. Assignment in expression

8. Changing return value ...

9. Implementation of sets ...

10. bag collection class




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