1

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

4 Answers 4

1

The easiest way is to JSON-encode it. See the json module.

Sign up to request clarification or add additional context in comments.

Comments

1

you have the str(res) and repr(res) function but you could also do ','.join(res)

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.