将文件逐行读入 Python 中的数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16222956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a file line by line into elements of an array in Python
提问by walterfaye
So in Ruby I can do the following:
所以在 Ruby 中,我可以执行以下操作:
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
How would one do that in Python?
在 Python 中如何做到这一点?
采纳答案by Rushy Panchal
testsite_array = []
with open('topsites.txt') as my_file:
for line in my_file:
testsite_array.append(line)
This is possible because Python allows you to iterate over the file directly.
这是可能的,因为 Python 允许您直接遍历文件。
Alternatively, the more straightforward method, using f.readlines():
或者,使用更直接的方法f.readlines():
with open('topsites.txt') as my_file:
testsite_array = my_file.readlines()
回答by Hunter McMillen
Just open the file and use the readlines()function:
只需打开文件并使用该readlines()功能:
with open('topsites.txt') as file:
array = file.readlines()
回答by Ashwini Chaudhary
In python you can use the readlinesmethod of a file object.
在python中,您可以使用readlines文件对象的方法。
with open('topsites.txt') as f:
testsite_array=f.readlines()
or simply use list, this is same as using readlinesbut the only difference is that we can pass an optional size argument to readlines:
或者简单地使用list,这与使用相同,readlines但唯一的区别是我们可以将一个可选的大小参数传递给readlines:
with open('topsites.txt') as f:
testsite_array=list(f)
help on file.readlines:
帮助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.

