开发者

Python: Spaces to Tabs?

I have a python file (/home/test.py) th开发者_如何学Pythonat has a mixture of spaces and tabs in it.

Is there a programmatic way (note: programmatic, NOT using an editor) to convert this file to use only tabs? (meaning, replace any existing 4-spaces occurrences with a single tab)?

Would be grateful for either a python code sample or a linux command to do the above. Thanks.


Sounds like a task for sed:

sed -e 's/    /\t/g' test.py > test.new

[Put a real tab instead of \t]

However...

Use 4 spaces per indentation level.

--PEP 8 -- Style Guide for Python Code


you can try iterating the file and doing replacing eg

import fileinput
for line in fileinput.FileInput("file",inplace=1):
    print line.replace("    ","\t")

or you can try a *nix tool like sed/awk

$ awk '{gsub(/    /,"\t")}1' file > temp && mv temp file

$ ruby -i.bak -ne '$_.gsub!(/    /,"\t")' file
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜