12

I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.

I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?

5 Answers 5

17

If there are not many files to convert, you can open them in vim, and use the :retab command.

See the vim documentation for more information.

16

Python includes a script for the opposite (tabs to spaces). It's C:\Python24\Tools\Scripts\reindent.py for me

2
  • This is not available under Linux, even on py26.
    – sorin
    Commented Jul 22, 2010 at 13:49
  • stringvar.expandtabs(tabsize=8) is the opposite. April 2018 v2.17
    – SDsolar
    Commented Apr 6, 2018 at 1:09
12

:retab will swap tab with spaces, and :retab! will swap spaces with tab. 1 tab = 4 spaces, 4 spaces = 1 tab, depending on your tab setting.

1
  • +1, didn't know it worked both ways; it uses the tabstop setting, presumably?
    – James
    Commented Feb 14, 2010 at 0:49
4

If you use Linux, you might also play around with unexpand:

Convert blanks in each FILE to tabs, writing to standard output. With no FILE, or when FILE is -, read standard input.

1
  • You'll find a win32 build if you want.
    – sorin
    Commented Jul 22, 2010 at 13:50
3

In emacs, M-x tabify will convert spaces to tabs where possible. You'll probably want to set the tab-width variable appropriately.

I don't know if this addresses your concern that spaces be interpreted in the same way as the python interpreter, but you could always load up python-mode and use M-x indent-region.

Not the answer you're looking for? Browse other questions tagged or ask your own question.