reading text files with indentation
Peter Otten
__peter__ at web.de
Mon Jul 28 03:45:33 EDT 2014
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")
More information about the Python-list
mailing list