Read file into list and strip newlines

后端 未结 3 605
盖世英雄少女心
盖世英雄少女心 2020-12-31 13:16

I\'m having issues in reading a file into a list, When I do it only creates one item from the entire file rather than reading each element into its own field. I\'m using

相关标签:
3条回答
  • 2020-12-31 13:40

    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
    
    0 讨论(0)
  • 2020-12-31 13:53

    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.

    0 讨论(0)
  • 2020-12-31 13:56

    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.

    0 讨论(0)
提交回复
热议问题