在Python中,我如何读取文件行

如何在Python中读取文件的每一行并将每行存储为列表中的元素?

我想逐行读取文件,并将每行添加到列表的末尾。


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


请参阅输入和输出:

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

或剥离换行符:

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

编者按:Janus Troelsen的评论暗示,这个答案的原始whitespace-stripping命令line.strip()会删除所有前导和尾随空白,而不仅仅是尾随的n


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

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

上一篇: In Python, how do I read a file line

下一篇: How do I copy a file in python?