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.
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()