pythonweb-scrapingfile-handlingpdf-scraping

file handling + word scraping (trying to find all the words in a file that end with 'y')


ERROR: Traceback (most recent call last): File "c:\Users\Pranjal\Desktop\tstp\zen_scraper.py", line 5, in words = re.findall("$y",file) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0\lib\re.py", line 241, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object PS C:\Users\Pranjal\Desktop\tstp>

import re

file = open("zen.txt",'r')

words = re.findall("$y",file)
print(words)

Solution

  • You have opened the file but you haven't got its content yet. Also, re is not necessary here, str.endswith() is all you need.

    with open("zen.txt",'r') as f:
        for line in f:
            for word in line.split():
                if word.endswith('y'):
                    print(word)