Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75302 > unrolled thread

Re: reading text files with indentation

Started byPeter Otten <__peter__@web.de>
First post2014-07-28 09:45 +0200
Last post2014-07-28 09:45 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: reading text files with indentation Peter Otten <__peter__@web.de> - 2014-07-28 09:45 +0200

#75302 — Re: reading text files with indentation

FromPeter Otten <__peter__@web.de>
Date2014-07-28 09:45 +0200
SubjectRe: reading text files with indentation
Message-ID<mailman.12380.1406533557.18130.python-list@python.org>
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()
>              policy_lines.append(line)
>              print line
> 
> Cheers

for line in files:
    with open(file) as lines:
        for line in lines: # you can iterate over the file directly;
                           # no need for the intermediate list built by
                           # the readlines() method
            line = line.partition("#")[0] # remove comment
            line = line.rstrip() # remove trailing whitespace
            policy_lines.append(line)
            print line


If you want to keep trailing whitespace other than the newline replace

line = line.rstrip()

with 

line = line.rstrip("\n\r")



[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web