<p>您得到错误是因为您试图使用一个变量<code>vt_result_file</code>,它不在您试图访问它的脚本部分中。您试图在这里使用它,大概是为了循环一组文件:</p>
<pre><code> for i in range(vt_result_file):
output.write(vt_result_file, vt_result_check(path))
</code></pre>
<p>但是<code>vt_result_file</code>只存在于<code>vt_result_check</code>函数中,当您试图使用<code>for i in range(vt_result_file)</code>中的变量时,它甚至还没有被调用。在</p>
<p>您也在重复工作,因为您的<code>vt_result_check</code>函数遍历目录中的所有文件,所以您不需要做同样的事情来获得结果。在</p>
<p>似乎您的main函数也无法正常工作,因为您正在遍历文件,将内容设置为<code>vt_data</code>,但您只对最后一组数据进行进一步分析:</p>
^{pr2}$
<p>我想您可能希望对每个文件运行分析代码,然后保存每个文件的结果。一种简单的方法是使用字典请参见<a href="https://docs.python.org/3/library/stdtypes.html#mapping-types-dict" rel="nofollow noreferrer">https://docs.python.org/3/library/stdtypes.html#mapping-types-dict</a>以下是关于如何重组代码的建议:</p>
<pre><code>def vt_result_check(path):
# initialise an empty dictionary for your results
results = {}
sample_types = ('detected_referrer_samples', 'detected_communicating_samples',
'detected_downloaded_samples', 'detected_urls')
threats = ("elevated exposure", "phishing and other frauds", "suspicious content")
for filename in os.listdir(path):
with open(path + filename, 'r') as vt_result_file:
# set this to false for each file
vt_result = False
vt_data = json.load(vt_result_file)
# do all your analysis here
vt_result |= any(sample['positives'] > 0 for sample_type in sample_types
for sample in vt_data.get(sample_type, []))
# Look for a Dr. Web category of known infection source
vt_result |= vt_data.get('Dr.Web category') == "known infection source"
# Look for a Forecepoint ThreatSeeker category of elevated exposure
# Look for a Forecepoint ThreatSeeker category of phishing and other frauds
# Look for a Forecepoint ThreatSeeker category of suspicious content
vt_result |= vt_data.get('Forcepoint ThreatSeeker category') in threats
# save the file name and the result in your dict
results[vt_result_file] = str(vt_result)
# return the dictionary
return results
</code></pre>
<p>然后,您可以将结果打印如下:</p>
<pre><code>if __name__ == '__main__':
result_dict = vt_result_check(path)
with open(file_n, 'w') as output:
for i in result_dict:
output.write(i + ": " + result_dict[i])
</code></pre>