Read file into list and strip newlines

末鹿安然 提交于 2019-11-30 14:49:24

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.

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.

This incorporates the strip directly into the for statement.

with open('drugs', 'r') as f:
  for line in map(lambda line: line.rstrip('\n'), f):
    print line

Or, if you know you don't need any space before or after text on a line, you can use this.

import string

with open('drugs', 'r') as f:
  for line in map(string.strip, f):
    print line
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!