I am a newbie and would like to extract dates from a txt file and write them to another file. Each date in one line. But I don't get how. I tried append but it won't work and this way it only writes the last date:
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)) ---EDIT--- I changed
f.write(contents) # writes contents correctly to file with Umlauts f.write(m.group(0)) to
with open("testoutput.txt", "a") as myfile: myfile.write(m.group(0)) Now it writes all Dates to the file, but it writes them directly after another. What do I have to add, if I want them below eachother?
Can anybody help?
best regards
open("testoutput.txt", "a")is what you're looking for. Furthermore, opening and writing to the file on each iteration is very slow - save in to a string and write it once afterwards.