Вопрос: В Python, как я могу прочитать файл по строкам в списке?


Как прочитать каждую строку файла в Python и сохранить каждую строку как элемент в списке?

Я хочу прочитать файл строки за строкой и добавить каждую строку в конец списка.


1652


источник


Ответы:


with open(fname) as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content] 

Я предполагаю, что вы имели в виду listа не массивом.


1596



Видеть Вход и выход :

with open('filename') as f:
    lines = f.readlines()

или с удалением символа новой строки:

lines = [line.rstrip('\n') for line in open('filename')]

Примечание редактора: оригинальная команда удаления пробелов в этом ответе, line.strip(), как это видно из комментария Януса Троелсена, удалит все ведущие и конечные пробелы, а не только конечные \n,


765



Это более очевидно, чем необходимо, но делает то, что вы хотите.

with open("file.txt", "r") as ins:
    array = []
    for line in ins:
        array.append(line)

354



This will yield an "array" of lines from the file.

lines = tuple(open(filename, 'r'))

200



If you want the \n included:

with open(fname) as f:
    content = f.readlines()

If you do not want \n included:

with open(fname) as f:
    content = f.read().splitlines()

147



You could simply do the following, as has been suggested:

with open('/your/path/file') as f:
    my_lines = f.readlines()

Note that this approach has 2 downsides:

1) You store all the lines in memory. In the general case, this is a very bad idea. The file could be very large, and you could run out of memory. Even if it's not large, it is simply a waste of memory.

2) This does not allow processing of each line as you read them. So if you process your lines after this, it is not efficient (requires two passes rather than one).

A better approach for the general case would be the following:

with open('/your/path/file') as f:
    for line in f:
        process(line)

Where you define your process function any way you want. For example:

def process(line):
    if 'save the world' in line.lower():
         superman.save_the_world()

(The implementation of the Superman class is left as an exercise for you).

This will work nicely for any file size and you go through your file in just 1 pass. This is typically how generic parsers will work.


89



If you don't care about closing the file, this one-liner works:

lines = open('file.txt').read().split("\n")

The traditional way:

fp = open('file.txt') # Open file on read mode
lines = fp.read().split("\n") # Create a list containing all lines
fp.close() # Close file

Using with (recommended):

with open('file.txt') as fp:
    lines = fp.read().split("\n")

59



This should encapsulate the open command.

array = []
with open("file.txt", "r") as f:
  for line in f:
    array.append(line)

36



Data into list

Assume that we have a text file with our data like in the following lines:

Text file content:

   line 1
   line 2
   line 3
  • Open the cmd in the same directory (right click the mouse and choose cmd or PowerShell)
  • Run python and in the interpreter write:

The Python script

>>> with open("myfile.txt", encoding="utf-8") as file:
...     x = [l.strip() for l in file]
>>> x
['line 1','line 2','line 3']

Using append

x = []
with open("myfile.txt") as file:
    for l in file:
        x.append(l.strip())

Or...

>>> x = open("myfile.txt").read().splitlines()
>>> x
['line 1', 'line 2', 'line 3']

Or...

>>> y = [x.rstrip() for x in open("my_file.txt")]
>>> y
['line 1','line 2','line 3']

35