tags:

views:

112

answers:

3

I am saving all the words from a file like so:

     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 okay when outputting it except the formatting. I am moving source code, is there any way I can save the indention?

+3  A: 

Since you state, that you want to move source code files, why not just copy/move them?

import shutil
shutil.move(src, dest)

If you read source file,

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

should load your file as it is (with indention), or not?

The MYYN
source code, not source code files. Sorry.
Thank you sir!!!
+1  A: 

Split removes all spaces:

>>> a="   a b   c"
>>> a.split(" ")
['', '', '', 'a', 'b', '', '', 'c']

As you can see, the resulting array doesn't contain any spaces anymore. But you can see these strange empty strings (''). They denote that there has been a space. To revert the effect of split, 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 spaces at the start of the line:

>>> import re
>>> re.match(r'^\s*', "   a b   c").group(0)
'   '
Aaron Digulla
+2  A: 

When you invoke line.split(), you remove all leading spaces.

What's wrong with just reading the file into a single string?

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