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

Reading a file line by line into elements of an array in Python

本问题已经有最佳答案,请猛点这里访问。

所以在Ruby中,我可以做到以下几点:

1
2
3
4
5
6
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end

在python中怎么做?


1
2
3
4
testsite_array = []
with open('topsites.txt') as my_file:
    for line in my_file:
        testsite_array.append(line)

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

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

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

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

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

或者简单地使用list,这与使用readlines是一样的,但唯一的区别是我们可以向readlines传递一个可选的大小参数:

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

关于file.readlines的帮助:

1
2
3
4
5
6
7
8
9
10
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.


只需打开文件并使用readlines()功能:

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