在Python中逐行读取文件到数组的元素中

这个问题在这里已经有了答案:

  • 在Python中,如何逐行读取文件到列表中? 35个答案

  • testsite_array = []
    with open('topsites.txt') as my_file:
        for line in my_file:
            testsite_array.append(line)
    

    这是可能的,因为Python允许你直接迭代文件。

    或者,更直接的方法,使用f.readlines()

    with open('topsites.txt') as my_file:
        testsite_array = my_file.readlines()
    

    只需打开文件并使用readlines()函数即可:

    with open('topsites.txt') as file:
        array = file.readlines()
    

    在python中,你可以使用文件对象的readlines方法。

    with open('topsites.txt') as f:
        testsite_array=f.readlines()
    

    或者简单地使用list ,这与使用readlines相同,但唯一的区别是我们可以将可选大小参数传递给readlines

    with open('topsites.txt') as f:
        testsite_array=list(f)
    

    帮助file.readlines

    In [46]: file.readlines?
    Type:       method_descriptor
    String Form:<method 'readlines' of 'file' objects>
    Namespace:  Python builtin
    Docstring:
    readlines([size]) -> list of strings, each a line from the file.
    
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.
    
    链接地址: http://www.djcxy.com/p/42341.html

    上一篇: Reading a file line by line into elements of an array in Python

    下一篇: How do you read a file into a list in Python?