0

I am writing code that looks for a specific string that could occur in a vacancy. I have some vacancies in a local folder in a .txt format. I want to search all files for the string and then store that string in a new file that will contain all filenames.

I created a list that contains all vacancies because I do not want the new file containing the searched string to appear when I search for a string a second time

I have the following code:

import os
import glob
from datetime import date
import time

today = date.today()
d1 = today.strftime("%d/%m/%Y")

search = "engineer"


vacancies = [filename for filename in glob.glob("*.txt") if not filename.endswith('keyword.txt')]

for filename in vacancies:
   with open ("C:\\LOCATION\\txt"+'\\'+filename, 'r', encoding='utf-8') as f: 
       for line in f:
           line = line.lower


for filename in vacancies:
    with open ("C:\\LOCATION\\txt"+'\\'+filename) as f:
     
        if search in f.read():
            f = open(d1 + " " + search + " keyword.txt","a+", encoding='utf-8')
            f.write("Found it in " + filename + '\n')
            f.close

I would expect my list to filter out the new file, however I get an errormessage stating: FileNotFoundError: [Errno 2] No such file or directory: '05/11/2020 engineer keyword.txt'

Can someone explain why this code is not working?

7
  • Side note: line = line.lower has no effect. Commented Nov 5, 2020 at 12:37
  • Could you provide example text. Commented Nov 5, 2020 at 12:37
  • Did you expect the file 05/11/2020 engineer keyword.txt to exist? Commented Nov 5, 2020 at 12:38
  • @mkrieger1 I would expect the file to be created if the word "engineer" would be found in at least one file of the files in the list. The list contains only the filenames, not the actual content with regard to the line=line.lower; thank you, I had not tested that line of code yet because of the primary issue. I would have tested that after. Any recommendations? Commented Nov 5, 2020 at 13:09
  • @AlexNe the list contains only filenames, not the actual content. What would you need? Commented Nov 5, 2020 at 13:10

1 Answer 1

1

The reason why the FileNotFoundError was given is because of the slashes in the d1 variable. The text file could not be created with slashes. After swapping slash"" for hyphen"-", the code worked just fine

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

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.