从文本文件python中读取 [英] Reading from a text file python

查看:66
本文介绍了从文本文件python中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数字矩阵的文本文件:

I have a text file which contains a matrix of numbers:

999 999  10  8
3 4 999 999 999 
6 999 2 7 999
999 6 3 5  6
999 9 1 10 999
10 6 999 2 2 999

我正在尝试读取每一行并将其存储到 Python 中的数组中,但是我无法将每个值从 string 更改为 int.我在解析每一行时尝试使用 int() 但我得到了无法将 list 传递到 int() 参数的错误.

I'm trying to read each line and store it into an array in Python but I'm having trouble changing each value into an int from a string. I tried using the int() when parsing each line but I get the error of not being able to pass list into the int() argument.

推荐答案

试试看:

matrix = [[int(i) for i in line.split()] for line in open('myfile.txt')]

如果您不想要第一行,请先阅读它.

[edit] if you don't want the first line just read it before.

with open('myfile') as f:
    f.readline()
    matrix = ....

这篇关于从文本文件python中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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