How to open, read a file line by line and write lines from a file with an array?

1 answer 1

with open("file.ext") as file: array = [row.strip() for row in file] 

A with expression will ensure that the file is closed after the work is finished. The expression that creates the array is called the list comprehension generator. Strings are searched inside it, it is equivalent to:

 for line in file.readlines(): # blah-blah 

Well, the strip() method removes extra spaces from the end and beginning of a line, including the line ending character. In case there is no need to trim the whitespace at the beginning of the line, you can use rstrip()

  • one
    Because array = file.readlines() author did not write about the line array = file.readlines() , one could simply write array = file.readlines() . - insolor
  • @insolor, did not write, but if the questioner has similar questions, you can play a telepath and trim the end of the line - this is a typical behavior when reading a text file. - m9_psy 5:58 pm
  • array = list (open ('text.txt')) or so - vadim vaduxa