I am trying to write the contents of a re.findall to a file. I tried
output_file.write (findall(tags_pattern, searchtext))
but I got a type error. How do I convert this to a type that can be written to a file?
Thanks
re.findall returns a list of matches found in searchtext for tags_pattern. Those matches are just strings. The easiest way to convert a list of strings into a single string which can be written to a file is to call str.join on a string representing the separator you want to insert between the strings in the list. For example, you may call '\n'.join(findall(tags_pattern, searchtext)) if you want to store each match on its own line.
The pickle module is built to quickly store Python structures in a file. It is not nearly as portable as JSON or some other serialization format, but depending on your purposes, it may be just enough.
To use pickle:
import re, pickle
r = re.findall(pattern, text)
with open('results.pkl', 'wb') as resultsfile:
pickle.dump(r, resultsfile)
To recover the list, use pickle.load:
with open('results.pkl', 'rb') as resultsfile:
r2 = pickle.load(resultsfile)
I'd be wary of using this in production code, or where you need to transmit the re.findall results to a web client, but for quick testing and local storage, this is probably the easiest.