1

Is there a way to open a file, if a word of the filename is contained in a string? Here I have stored the word keys in the variable 'query', I want that if the word 'keys' is the value of the string 'query', it should open the file 'keys in drawer.txt' as it contains the word keys, or if the value is of 'query' is 'pen', it should open the file 'pen on table'.txt. Here is the pen on table.txt file:

pen is on the table

keys in drawer.txt

the keys are in the drawer

How do I do this? I know this is a bit complicated, but please try to answer this question, I am on this from the last 2 days!

query=("keys")
list_directory=listdir("E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\")
     
 if query in list_directory: 
                with open(f"E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\ 
                {list_directory}",'r') as file:
                    read_file=file.read
                    print(read_file)
                    file.close
                    pass

This code does not work for some reason.

  • Why a ```pass``` after the ```fil.close()``` method –  Aug 17 '21 at 16:30
  • By looking at the code, ```with open(f"E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\{list_directory}.txt",'r')```, you have probably forgotten the ```.txt``` extension –  Aug 17 '21 at 16:32

2 Answers2

2

read() and close() are methods, not properties. You should write file.read() instead of file.read. In addition, it's redundant to close the file when using the with keyword.

Jonathan
  • 88
  • 1
  • 8
0

list_directory is a list of strings, not a string. This means that you need to iterate over it in order to compare each string in the list to your query.

You also need to call the file.read and file.close methods by adding parenthesis to them (file.read(), file.close()), or else they won't execute.

This reworked code should do the trick:

query = "keys"
path = "E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\"

list_directory = listdir(path)
for file_name in list_directory:
    if query in file_name:
        with open(f"{path}{file_name}",'r') as file:
            content = file.read()
            print(content)
            file.close()
jfaccioni
  • 7,099
  • 1
  • 9
  • 25