在Python中将文件逐行读入数组元素
因此,在Ruby中,我可以执行以下操作:在Python中将文件逐行读入数组元素,python,arrays,file,readline,Python,Arrays,File,Readline,因此,在Ruby中,我可以执行以下操作: testsite_array = Array.new y=0 File.open('topsites.txt').each do |line| testsite_array[y] = line y=y+1 end 在Python中如何实现这一点?只需打开文件并使用readlines()函数: with open('topsites.txt') as file: array = file.readlines() 这是可能的,因为Python允许
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
在Python中如何实现这一点?只需打开文件并使用
readlines()
函数:
with open('topsites.txt') as file:
array = file.readlines()
这是可能的,因为Python允许您直接迭代文件
或者,更直接的方法是使用:
在python中,可以使用文件对象的
readlines
方法
with open('topsites.txt') as f:
testsite_array=f.readlines()
或者简单地使用list
,这与使用readlines
相同,但唯一的区别是我们可以将可选的size参数传递给readlines
:
with open('topsites.txt') as f:
testsite_array=list(f)
有关文件的帮助。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.
[46]:file.readlines中的?
类型:方法描述符
字符串形式:
名称空间:Python内置
文档字符串:
readlines([size])->字符串列表,每个字符串都是文件中的一行。
反复调用readline(),并返回所读取的行的列表。
可选的size参数(如果给定)是
返回的行中的总字节数。
with open('topsites.txt') as f:
testsite_array=list(f)
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.