【发布时间】:2017-03-19 15:57:52
【问题描述】:
我是新手,想从 txt 文件中提取日期并将它们写入另一个文件。每个日期在一行中。但我不明白怎么做。我试过追加,但它不起作用,这样它只写最后一个日期:
f = open("Krupp.txt", "r")
contents = f.read()
f.close() #close the file
# finditer
# finds all Dates and shows them in a List (Montag, 15. März 2013)
for m in re.finditer("(Montag|Dienstag|Mittwoch|Donnerstag|Freitag|Samstag|Sonnabend|Sonntag)(, )([123][0-9]|[1-9])(. )(Januar|Februar|März|April|Mai|Juni|Juli|August|September|Oktober|November|Dezember)( )([0-2][0-9][0-9][0-9])", contents):
print m.group(0)
# changed
with open("testoutput.txt", "a") as myfile:
myfile.write(m.group(0))
---编辑--- 我变了
f.write(contents) # writes contents correctly to file with Umlauts
f.write(m.group(0))
到
with open("testoutput.txt", "a") as myfile:
myfile.write(m.group(0))
现在它将所有日期写入文件,但它直接一个接一个地写入它们。如果我希望它们彼此低于,我必须添加什么?
有人可以帮忙吗?
最好的问候
【问题讨论】:
-
请提供有关此的更多详细信息。提供文件外观的示例。你从你的正则表达式匹配中得到什么吗?此外,每次以“写入”模式打开文件时,您也会不断地覆盖循环内的文件。您想在循环之外打开文件然后写入。
-
您只是在每次迭代中覆盖您的文件,也许
open("testoutput.txt", "a")是您正在寻找的。此外,在每次迭代时打开和写入文件非常慢 - 保存到字符串中,然后再写入一次。
标签: python python-2.x