【发布时间】:2021-12-31 05:06:25
【问题描述】:
我有以下文件夹结构:
root
│ file001.docx
│ file002.docx
│
└───folder1
│ file003.docx
│ file004.docx
│
└───subfolder1
│ file005.docx
│ file006.docx
|____subfolder2
|
|_file007.docx
我希望创建一个程序,当有人键入他们的根目录和关键字时,该文件就会显示出来。例如:如果我输入“hello there!”,file007.docx 将出现(假设文本“hello there!”包含在 file007.docx 中)并让用户知道输入的单词在单词 doc 中。
为了解决这个问题,我使用以下代码列出了文件夹和子文件夹中的所有 word 文档:
def find_doc():
variable= input('What is your directory?') #asking for root directory
os.chdir(variable)
files = []
for dirpath, dirnames, filenames in os.walk(variable):
for filename in [f for f in filenames if f.endswith(".docx")]:
files.append(filename)
return files
现在,这是在每个 word 文档中查找内容的第二个代码:
all_files= find_doc() # just calling the first function I just made
while True:
keyword= input('Input your word or type in Terminate to exit: ')
for i in range(len(all_files)):
text = docx2txt.process(all_files[i])
if keyword.lower() in text.lower(): #to make it case insensitive
print ((all_files[i]))
if keyword== ('Terminate') or keyword== ('terminate'):
break
理论上,如果我输入单词“hello”,在输入:input('Input your word or type in Terminate to exit: '),我应该能够检索到file007.docx,因为all_files= find_doc() 输出
['file001.docx',
'file002.docx',
'file003.docx',
'file004.docx',
'file005.docx',
'file006.docx',
'file007.docx',]
由于os.walk() 的递归性质。
但是,它给了我一个错误:FileNotFoundError: [Errno 2] No such file or directory:
我想知道我哪里出错了?谢谢!
【问题讨论】:
-
您附加了文件名,但不是
files的完整路径。除非您存储它们的完整路径,或者至少是相对于脚本工作目录的路径,否则无法找到这些文件。 -
您只检索了不在您的工作目录中的文件名。这就是你得到 FIleNotFoundError 的原因。因此,您需要在第一个函数中提取路径+文件名。
-
@MitchellOlislagers 我需要使用字典吗?这样做?
标签: python recursion binary-search-tree binary-search python-docx