A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.