In Python, how do I read a file line

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.


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而不是数组。


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 .


这比必要更明确,但是做你想要的。

with open("file.txt", "r") as ins:
    array = []
    for line in ins:
        array.append(line)
链接地址: http://www.djcxy.com/p/1126.html

上一篇: 你如何追加到一个文件?

下一篇: 在Python中,我如何读取文件行