<p>您试图构建的函数检查一个单词(即<code>name_of_signal</code>)是否不在目录</em><br/>中的任何文件中
这意味着,如果至少有一个文件包含<code>name_of_signal</code>,则返回<code>False</code>;如果所有文件都不包含<code>name_of_signal</code>,则返回<code>True</code>。你知道吗</p>
<p>这可以被概念化为:</p>
<blockquote>
<p>For each file in my folder, open the file and check if it contains the word <code>name_of_signal</code>. If the word is in the file, you can stop the iteration and return <code>False</code> (since the requirement is <em>at least one file</em>). If the word is not in the file, continue with the next file</p>
</blockquote>
<p>您的函数是正确的,但它检查的结果正好相反:不是检查<em>任何文件</em>中是否包含单词,而是检查<em>是否至少在文件</em>中包含单词:</p>
<pre><code>def not_existing_signals(name_of_signal): # FUNCTION DEFINITION
for filename in Path('c:\....').glob('**/*.txt') : # for each file in folder
with open(filename) as f: # open the file
if name_of_signal in f.read(): # if name_of_signal is in the file
return True # stop the iteration and return True
return False # if we've looked inside all the files and didn't found name_of_signal, return False
</code></pre>
<p><strong>解决方案:</strong></p>
<p>解决方法是将<code>return True</code>与<code>return False</code>交换:</p>
<pre><code>def not_existing_signals(name_of_signal): # FUNCTION DEFINITION
for filename in Path('c:\....').glob('**/*.txt') : # for each file in folder
with open(filename) as f: # open the file
if name_of_signal in f.read(): # if name_of_signal is in the file
return False # stop the iteration and return False (MEANS: found at least one file with name_of_signal
return True # if we've looked inside all the files and didn't found name_of_signal, return True (MEANS: name_of_signals is not in the files!)
</code></pre>
<p>如果不想更改代码,只需更改函数名即可:</p>
<p>从<code>not_existing_signals</code>到<code>existing_signals</code>!!你知道吗</p>