首页 > 解决方案 > Reading file and getting values from a file. It shows only first one and others are empty

问题描述

I am reading a file by using a with open in python and then do all other operation in the with a loop. While calling the function, I can print only the first operation inside the loop, while others are empty. I can do this by using another approach such as readlines, but I did not find why this does not work. I thought the reason might be closing the file, but with open take care of it. Could anyone please suggest me what's wrong

def read_datafile(filename):
     with open(filename, 'r') as f:
            a = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==2]
            b = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==3]
            c = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==2]
     return a, b, c

read_datafile('data_file_name')

I only get values for a and all others are empty. When 'a' is commented​, I get value for b and others are empty.

Updates The file looks like this:

 -0.6908270760153553 -0.4493128078936575  0.5090918714784820
  0.6908270760153551 -0.2172871921063448  0.5090918714784820
 -0.0000000000000000  0.6666999999999987  0.4597549674638203
  0.3097856229862140 -0.1259623621214220  0.5475896447896115
  0.6902143770137859  0.4593623621214192  0.5475896447896115

标签: python-3.x

解决方案


构造

with open(filename) as handle:
    a = [line for line in handle if condition]
    b = [line for line in handle]

将始终返回一个空b,因为迭代器a已经消耗了打开文件句柄中的所有数据。一旦到达流的末尾,其他读取任何内容的尝试都不会返回任何内容。

如果输入是可搜索的,您可以将其倒回并再次读取所有相同的行;或者您可以close(显式或隐式地离开该with块)并再次打开它 - 但更有效的解决方案是只读取一次,然后从内存中选择您真正想要的行。请记住,从磁盘读取一个字节可能比从内存中读取一个字节要多几个数量级的时间。请记住,您读取的数据可能来自不可搜索的来源,例如来自另一个进程的标准输出,或网络连接另一端的客户端。

 def read_datafile(filename):
     with open(filename, 'r') as f:
         lines = [line for line in f]
     a = lines[2]
     b = lines[3]
     c = lines[2]
     return a, b, c

如果文件太大而无法立即放入内存,那么您最终会遇到一系列不同的问题。也许在这种情况下,您似乎只想要从一开始的几行,首先只将那么多行读入内存。


推荐阅读