gpt4 book ai didi

python - 将整个正则表达式组导出到文本文件

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:19 24 4
gpt4 key购买 nike

当我打印组“print(a)”时,会显示整个组。当我将它保存到文本文件时 "open("sirs1.txt", "w").write(a)" 只有最后一行被保存到文件中。

import re

def main():
f = open('sirs.txt')
for lines in f:
match = re.search('(AA|BB|CC|DD)......', lines)
if match:
a = match.group()
print(a)
open("sirs1.txt", "w").write(a)

如何将整个组保存到文本文件。

最佳答案

nosklo 是正确的主要问题是每次写入时都会覆盖整个文件。 mehmattski 也是正确的,因为您还需要在每次写入时显式添加\n 以使输出文件可读。

试试这个:

enter code here

import re

def main():
f = open('sirs.txt')
outputfile = open('sirs1.txt','w')

for lines in f:
match = re.search('(AA|BB|CC|DD)......', lines)
if match:
a = match.group()
print(a)
outputfile.write(a+"\n")

f.close()
outputfile.close()

关于python - 将整个正则表达式组导出到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com