python - 将文件逐行读取到 Python 中的数组元素中

标签 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 中做到这一点?

最佳答案

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/

相关文章:

javascript - 构建 n 进制数字数组的通用公式

java - 避免数组中出现重复的条目

python - 比 np.meshgrid 更有效的多维状态 Action 空间平铺方法?

javascript - 从插件获取本地文件到javascript

c - c中的文件输入输出流

python - 根据 pandas 中的另一列对唯一值进行排序

python - 当表单操作设置为 "."时,Django 重定向到不同的 View

python - mypy:多种类型的类型注释列表的正确方法

python - 字段计算器和 Python 3 字符串重分类警告

c++ - 以正确的方式使用 C/C++ 读取文件格式