In Python, calling e.g. temp = open(filename,'r').readlines() results in a list in which each element is a line from the file. However, these strings have a newline character at the end, which I don’t want.
How can I get the data without the newlines?
You can read the whole file and split lines using
str.splitlines:Or you can strip the newline by hand:
Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.
This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).
If you want to avoid this you can add a newline at the end of file:
Or a simpler alternative is to
stripthe newline instead:Or even, although pretty unreadable:
Which exploits the fact that the return value of
orisn’t a boolean, but the object that was evaluated true or false.The
readlinesmethod is actually equivalent to:Since
readline()keeps the newline alsoreadlines()keeps it.Note: for symmetry to
readlines()thewritelines()method does not add ending newlines, sof2.writelines(f.readlines())produces an exact copy offinf2.