How to read a file line-by-line into a list?

2018-12-30 23:48发布

How do I read every line of a file in Python and store each line as an element in a list?

I want to read the file line by line and append each line to the end of the list.

30条回答
浅入江南
2楼-- · 2018-12-31 00:03

I'd do it like this.

lines = []
with open("myfile.txt") as f:
    for line in f:
        lines.append(line)
查看更多
永恒的永恒
3楼-- · 2018-12-31 00:05

Use this:

import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values

data is a dataframe type, and uses values to get ndarray. You can also get a list by using array.tolist().

查看更多
余欢
4楼-- · 2018-12-31 00:06

See Input and Ouput:

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

or with stripping the newline character:

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

Editor's note: This answer's original whitespace-stripping command, line.strip(), as implied by Janus Troelsen's comment, would remove all leading and trailing whitespace, not just the trailing \n.

查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 00:06

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

lines = tuple(open(filename, 'r'))
查看更多
牵手、夕阳
6楼-- · 2018-12-31 00:07

Just use the splitlines() functions. Here is an example.

inp = "file.txt"
data = open(inp)
dat = data.read()
lst = dat.splitlines()
print lst
# print(lst) # for python 3

In the output you will have the list of lines.

查看更多
梦寄多情
7楼-- · 2018-12-31 00:08

If you'd like to read a file from the command line or from stdin, you can also use the fileinput module:

# reader.py
import fileinput

content = []
for line in fileinput.input():
    content.append(line.strip())

fileinput.close()

Pass files to it like so:

$ python reader.py textfile.txt 

Read more here: http://docs.python.org/2/library/fileinput.html

查看更多
登录 后发表回答