python如何导入txt文件-如何读取文本文件导入列表或数组与Python

1586010002-jmsa.png

I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.

The text file is formatted as follows:

0,0,200,0,53,1,0,255,...,0.

Where the ... is above, there actual text file has hundreds or thousands more items.

I'm using the following code to try to read the file into a list:

text_file = open("filename.dat", "r")

lines = text_file.readlines()

print lines

print len(lines)

text_file.close()

The output I get is:

['0,0,200,0,53,1,0,255,...,0.']

1

Apparently it is reading the entire file into a list of just one item, rather than a list of individual items. What am I doing wrong?

解决方案

You will have to split your string into a list of values using split()

So,

lines = text_file.read().split(',')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值