This question already has answers here:
How to read a file line-by-line into a list?

(28个答案)


6年前关闭。




因此,在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()

08-16 10:57