逐行读取文件中的行到了一个Python数组中的元素 [英] Reading a file line by line into elements of an array in Python

查看:739
本文介绍了逐行读取文件中的行到了一个Python数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,在Ruby中,我可以做到以下几点:

  testsite_array = Array.new
Y = 0
File.open('topsites.txt')每做|。线|
testsite_array [Y] =行
Y = Y + 1
结束

如何将一个做到这一点在Python?


解决方案

  testsite_array = []
开放('topsites.txt')为my_file:
    在my_file行:
        testsite_array.append(线)

这是可能的,因为Python允许您将文件直接迭代。

另外,更简单的方法,使用 f.readlines()

 开放('topsites.txt')为my_file:
    testsite_array = my_file.readlines()

So in Ruby I can do the following:

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?

解决方案

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.

Alternatively, the more straightforward method, using f.readlines():

with open('topsites.txt') as my_file:
    testsite_array = my_file.readlines()

这篇关于逐行读取文件中的行到了一个Python数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆