How to open, read a file line by line and write lines from a file with an array?
- onehmmm ... weird you are looking for ... - MaxU
- association: stackoverflow.com/questions/3277503 - Nicolas Chabanovsky ♦
|
1 answer
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()
- oneBecause
array = file.readlines()
author did not write about the linearray = file.readlines()
, one could simply writearray = 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
|