I'm not quite sure if you really want to remove all escaped characters of just the trailing \n
at the end of each line. This is a common problem many python-programmers have when first reading files, I had it myself a while ago.
readlines()
keeps the trailing \n
, so that a simple "".join(lines)
would restore the original file content.
Just strip the trailing \n
from each line.
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip()
print line
lines2.append(line)
fh.close()
The output will be
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip("\n")
print line
lines2.append(line)
fh.close()
# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys
lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
print line
lines1.append(line)
fh.close()
lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
line = line.rstrip("\n")
print line
lines2.append(line)
fh.close()
You could also write line.rstrip("\n")
to explicitly only strip the newline characters and not all whitespace characters.