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


a source to share


3 answers


When you call line.split()

, you strip all leading spaces.

What's wrong just by reading the file on one line?



textWithIndentation = open(sys.argv[1], "r").read()

      

+2


a source


Since you are stating that you want to move your source files, why not just copy / move them?

import shutil
shutil.move(src, dest)

      

If you are reading the original file,



fh = open("yourfilename", "r")
content = fh.read()

      

should your file load as is (indented) or not?

+3


a source


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







All Articles