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

问题描述:

所以在Ruby中我可以做到以下几点:逐行读取文件中的行到一个数组中的元素在Python

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

如何将一个做到这一点在Python?

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

在蟒可以使用文件对象的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.