22

因此,在 Ruby 中,我可以执行以下操作:

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

在 Python 中如何做到这一点?

4

3 回答 3

40
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()
于 2013-04-25T19:17:20.387 回答
8

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

with open('topsites.txt') as file:
    array = file.readlines()
于 2013-04-25T19:17:20.210 回答
7

在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.
于 2013-04-25T19:17:39.063 回答