如何在python中从文本文件中读取特定的行?

2024-10-01 19:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含大量数据的文本文件。我希望能够读取文本文件并编写新的文本文件。但是在新的文本文件中,我不希望它包含原始文件的某些部分。在

例如,文本文件

------------------------
Age: 39
Gender: Female
Smoking: Yes
remarks: something about the person
-----------------------
Age: 52
Gender: Male
Smoking: Yes
remarks: something about the person
-----------------------

如何使新文件只读取年龄和性别,使新文本文件看起来像(还包括分隔每个条目的短划线):

^{pr2}$

我看到了一些代码和其他问题,但它们都不只是删除特定的行。在


Tags: 文件the数据agegendersomethingmalefemale
2条回答
import re

file = open('filename.txt','rb').read()

a = re.findall(r'Age: (\d+)\nGender: (Male|Female)', file)

print "           -"
for n in a:
    print 'Age: '+n[0]+'\nGender: '+n[1]
    print "           -"

你可以更懒,在正则表达式中也抓取破折号

^{pr2}$
with open('path/to/infile') as infile, open('path/to/outfile', 'w') as outfile:
    for line in infile:
        if line.startswith(("Age", "Gender", "  ")):
            outfile.write(line)

或者使用grep

^{pr2}$

相关问题 更多 >

    热门问题