python 遍历文件内容,Python循环遍历读取数据的文本文件

I am new to python, and although I am sure this might be a trivial question, I have spent my day trying to solve this in different ways. I have a file containing data that looks like this:

data

data

...

data

data

...

And that extends a number of times... I need to read the "data" which for the first set (between the first and second ) contains a number N1 of X points, a number N2 of Y points and a number N1*N2 of Z points. If I had only one set of data I already know how to read all the data, then read the value N1, N2, then slice it into X, Y and Z, reshape it and use it... but if my file contains more than one sets of data, how do I read only from one string until the next one, and then repeat the same operation for the next set, and again until I reach the end of the file?

I tried defining a function like:

def dat_fun():

with open("inpfile.txt", "r") as ifile:

for line in ifile:

if isinstance('line', str) or (not line):

break

for line in ifile:

yield line

but is not working, I get arrays with no data on them. Any comments will be appreciated.

Thanks!

解决方案

All lines are instances of str, so you break out on the first line. Remove that test, and test for an empty line by stripping away whitespace first:

def dat_fun():

with open("inpfile.txt", "r") as ifile:

for line in ifile:

if not line.strip():

break

yield line

I don't think you need to break at an empty line, really; the for loop ends on its own at the end of the file.

If your lines contain other sorts of data, you'd need to do the conversion yourself, coming from string.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值