【发布时间】:2021-08-17 15:48:30
【问题描述】:
如果文件名的单词包含在字符串中,有没有办法打开文件?在这里,我将单词键存储在变量'query'中,我希望如果单词'keys'是字符串'query'的值,它应该打开文件'keys indrawer.txt',因为它包含单词键,或者如果'query'的值是'pen',它应该打开文件'pen on table'.txt。 这是table.txt文件上的笔:
pen is on the table
drawer.txt 中的键
the keys are in the drawer
我该怎么做?我知道这有点复杂,但请尝试回答这个问题,我从过去 2 天开始就在这个问题上!
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
此代码由于某种原因不起作用。
【问题讨论】:
-
为什么
pass在fil.close()方法之后 -
通过查看代码
with open(f"E:\\Python_Projects\\Sandwich\\user_data\\Remember things\\{list_directory}.txt",'r'),您可能忘记了.txt扩展
标签: python file directory txt listdir