reading text files with indentation

Gary Herron gary.herron at islandtraining.com
Mon Jul 28 09:39:51 CEST 2014


On 07/27/2014 11:25 PM, Noah wrote:
> Hi there,
>
> The following code I am using to read in lines from a text file. The 
> indentation of the text is getting lost.  How can I correct that?
>
>
>     for file in files:
>           with open (file, "r") as file:
>         lines = file.readlines()
>
>     for line in lines:
>             line = re.sub("#.*", "", line)
>             line = line.strip()

The *strip* method on strings removes all whitespace from both ends.  
There goes your indentation.

> policy_lines.append(line)
>             print line
>
> Cheers

Example:

 >>> "   abc   ".strip()
'abc'


Gary Herron

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140728/01497888/attachment.html>


More information about the Python-list mailing list