<分区>
所以在 Ruby 中我可以做以下事情:
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
如何在 Python 中做到这一点?
<分区>
所以在 Ruby 中我可以做以下事情:
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()
关于python - 将文件逐行读取到 Python 中的数组元素中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222956/