在Python中逐行读取文件并将其存入数组元素中

28

那么在 Ruby 中,我可以做如下操作:

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

用Python应该如何实现这个功能呢?

3个回答

50
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()

12

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

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

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接