Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #75302
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: reading text files with indentation |
| Date | 2014-07-28 09:45 +0200 |
| Organization | None |
| References | <53D5ECD0.8010702@enabled.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.12380.1406533557.18130.python-list@python.org> (permalink) |
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")
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: reading text files with indentation Peter Otten <__peter__@web.de> - 2014-07-28 09:45 +0200
csiph-web