Python Forum

Full Version: TypeError: 're.Match' object is not iterable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was writing the following Python Code for copying search results (phone numbers) to a new .txt file and I got a TypeError. Please what other way can use to copy the "match" in the for loop to a new file?

Please help you if you can... Thanks!

import re
pattern = re.compile(r"\+\d\d\d\d\d\d\d\d\d\d\d\d\d")

with open("Tunj1.txt", "r") as wadb:
    init_content = wadb.read()

matches = pattern.finditer(init_content)

for match in matches:
    print(match)
    with open("Extracted Numbers.txt", "w") as wadb_Extracted:
        for line in match:
            wadb_Extracted.write(line)

Error:
Traceback (most recent call last): File "C:/Users/Charles Auspicks/PycharmProjects/HelloWorld/app.py", line 14, in <module> for line in match: TypeError: 're.Match' object is not iterable
matches is an iterator that returns Match objects.

Match objects themselves have information inside, but are not themselves iterable. So when you do for line in match, the iteration attempt fails.