How to preserve file indentation format in Python
I save all words from a file like this:
sentence = " "
fileName = sys.argv[1]
fileIn = open(sys.argv[1],"r")
for line in open(sys.argv[1]):
for word in line.split(" "):
sentence += word
Everything works fine on output except formatting. I am moving the source code, is there a way to keep the indentation?
+1
robertd
a source
to share
3 answers
Split removes all spaces:
>>> a=" a b c"
>>> a.split(" ")
['', '', '', 'a', 'b', '', '', 'c']
As you can see, the resulting array no longer contains spaces. But you can see these strange blank lines (''). They mean there was space. To revert the split effect use join(" ")
:
>>> l=a.split(" ")
>>> " ".join(l)
' a b c'
or in your code:
sentence += " " + word
Or, you can use a regular expression to get all the spaces at the beginning of a line:
>>> import re
>>> re.match(r'^\s*', " a b c").group(0)
' '
+1
a source to share