Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从python中的大数据文件中读取某些行集?_Python_Header_Row - Fatal编程技术网

如何从python中的大数据文件中读取某些行集?

如何从python中的大数据文件中读取某些行集?,python,header,row,Python,Header,Row,假设我有一个包含重复标题的数据文件。我需要读取的行包括在和之间,如下所示: Header :Hellow World Header :Hellow World # 0.326681 11.7083 0 4.34818 12.222 0 7.56993 12.5076 0 5.55984 11.798 0 6.77682 11.7432 0 4.44614 11.0851 0 6.77111 10.4761 0 _ Header :Hellow World Header :H

假设我有一个包含重复标题的数据文件。我需要读取的行包括在和之间,如下所示:

Header :Hellow World  
Header :Hellow World
#
0.326681 11.7083 0 
4.34818 12.222 0 
7.56993 12.5076 0 
5.55984 11.798 0 
6.77682 11.7432 0 
4.44614 11.0851 0 
6.77111 10.4761 0 
_
Header :Hellow World  
Header :Hellow World
#
0.126018 2.98437 0 
0.855801 3.76535 0 
0.216594 0.154549 0 
4.38824 1.92399 0 
5.67207 1.28992 0 
5.28882 0.231295 0 
_
etc....
我编写了一个代码,以便只提取和之间的行,并在每个列表之前编写I'th_列表。关键是我的代码永远在终端中运行,不会停止。有人能帮我理解我的问题吗

f=open("f1.txt","w")
ff=open("f2.txt","r")

parsing=False
i=0
for line in ff:
    if line.startswith("#"):
        parsing=True
        f.write("#"+str(i)+"\n")
        i=i+1
    while parsing==True:
        f.write(ff.readline())
        if line.startswith("_"):
            break
    parsing=False 

ff.close()
f.close

在while循环中,您正在使用ff.readline函数读取行,但在下一行代码中,您正在使用不同的“行”来检查它是否以“\”开头

f=open("f1.txt","w")
ff=open("no_header.txt","r")

parsing=False
i=0
for line in ff:
    if line.startswith("#"):
        parsing=True
        f.write("#"+str(i)+"\n")
        i=i+1
    while parsing==True:
        # Your code was not correct from this point
        current_line = ff.readline()
        if current_line.startswith("_"):
            break
        f.write(current_line)
    parsing=False 

ff.close()
f.close

问题是您的代码在解析==True循环时永远不会离开循环。 我也不知道readline方法做什么,但它似乎不适合您的代码。 工作代码:

f=open("f1.txt","w")
ff=open("f2.txt","r")

parsing=False
i=0
for line in ff:
    if line.startswith("#"):
        parsing=True
        f.write("#"+str(i)+"\n")
        i=i+1
        continue
    if parsing:
        if line.startswith("_"):
            parsing=False
            continue
        f.write(line) 

ff.close()
f.close()

注:别忘了ff.close的括号-

代码没有读取作为ff打开的整个文件。因此,作为f打开的文件没有完全写入@斯文的答案很好,我的代码也很好。唯一的区别是@Sven编写了几乎所有的新代码。我对您的代码做了最小的更改,以便您能够更好地理解。