Python从文件中提取数据 [英] Python to extract data from a file
本文介绍了Python从文件中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
----
data1我试图提取具有特定文本文件的文本:
data1
data1
extractme
----
data2
data2
data2
----
data3
data3
extractme
----
然后将其转储到文本文件中,以便
----
$ p $对于我来说,这个功能已经足够好了。
data1
data1
data1
extractme
---
data3
data3
extractme
---
感谢您的帮助。
解决方案您的示例数据在一个名为data.txt的文件中,输出到result.txt。
$ p $inFile = open (data.txt)
outFile = open(result.txt,w)
buffer = []
keepCurrentSet = True
inFile:
buffer.append(line)
如果line.startswith(----):
#----开始一个新的数据集
如果keepCurrentSet:
outFile.write(。join(buffer))
#now重置我们的状态
keepCurrentSet = False
buffer = []
elif line.startswith(extractme) :
keepCurrentSet = True
inFile.close()
outFile.close()
I am trying to extract the text between that has specific text file:
----
data1
data1
data1
extractme
----
data2
data2
data2
----
data3
data3
extractme
----
and then dump it to text file so that
----
data1
data1
data1
extractme
---
data3
data3
extractme
---
Thanks for the help.
解决方案
This works well enough for me. Your sample data is in a file called "data.txt" and the output goes to "result.txt"
inFile = open("data.txt")
outFile = open("result.txt", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
buffer.append(line)
if line.startswith("----"):
#---- starts a new data set
if keepCurrentSet:
outFile.write("".join(buffer))
#now reset our state
keepCurrentSet = False
buffer = []
elif line.startswith("extractme"):
keepCurrentSet = True
inFile.close()
outFile.close()
这篇关于Python从文件中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文