loading...

Discussion on: 10 Awesome Pythonic One-Liners Explained

Collapse
paddy3118 profile image
Paddy3118
  1. Read file into array of lines

Needs to use rstrip rather than strip if you want to preserve left-hand whitespace in lines.

Collapse
devmount profile image
Andreas Author

Thank you for this addition. In this example I just wanted to strip both ends. To only remove the linebreaks, you have to specify the linebreak character:

c = [line.rstrip('\n') for line in open('file.txt')]
Collapse
anharrington profile image
Andrew N. Harrington

If you know the last line of the file does have a '\n', then line[:-1] is shorter.

Thread Thread
devmount profile image
Andreas Author

Indeed, thank you!

Thread Thread
paddy3118 profile image
Paddy3118

That's a big if. rstrip('\n') or simple rstrip() i find easier to read and less error prone.