正在尝试将文件名写入cs

2024-03-29 06:15:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码确定文件内容是返回True还是False,并将结果输出到.csv。在

我想把文件名也写到csv的同一行。在

错误消息

for i in range(vt_result_file):
NameError: name 'vt_result_file' is not defined

编码

^{pr2}$

Tags: 文件csv代码infalsetrue消息内容
2条回答

vt_result_file仅作为vt_result_check局部变量存在,您的错误是说该变量不存在于文件的底部。在

另外,(即使这无关紧要)在调用创建变量的函数之前,您引用的是该变量。在


在主功能区没有任何循环。而您的check函数只返回一个值。在

因此,您只能写出一个CSV行

if __name__ == '__main__':
    with open(file_n, 'w') as output:
        writer = csv.writer(output)
        writer.writerow([file_n, vt_result_check(path)])

编辑

关于你的评论,你想要这样的东西

^{pr2}$

您得到错误是因为您试图使用一个变量vt_result_file,它不在您试图访问它的脚本部分中。您试图在这里使用它,大概是为了循环一组文件:

    for i in range(vt_result_file):
        output.write(vt_result_file, vt_result_check(path))

但是vt_result_file只存在于vt_result_check函数中,当您试图使用for i in range(vt_result_file)中的变量时,它甚至还没有被调用。在

您也在重复工作,因为您的vt_result_check函数遍历目录中的所有文件,所以您不需要做同样的事情来获得结果。在

似乎您的main函数也无法正常工作,因为您正在遍历文件,将内容设置为vt_data,但您只对最后一组数据进行进一步分析:

^{pr2}$

我想您可能希望对每个文件运行分析代码,然后保存每个文件的结果。一种简单的方法是使用字典请参见https://docs.python.org/3/library/stdtypes.html#mapping-types-dict以下是关于如何重组代码的建议:

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

然后,您可以将结果打印如下:

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])

相关问题 更多 >