Read file into list and strip newlines
If you're okay with reading the entire file's contents into memory, you can also use str.splitlines()
with open('your_file.txt') as f:
lines = f.read().splitlines()
splitlines()
is similar to split('\n')
but if your file ends with a newline, split('\n')
will return an empty string at the very end, whereas splitlines()
handles this case the way you want.
file.read()
reads entire file's contents, unless you specify max length. What you must be meaning is .readlines()
. But you can go even more idiomatic with a list comprehension:
with open('drugs') as temp_file:
drugs = [line.rstrip('\n') for line in temp_file]
The with
statement will take care of closing the file.