读取目录中的所有文件,并确定它们在任何条件下是否返回True或False



我有一个python脚本,我试图读取目录中的所有.txt文件,并确定它们在脚本中的任何条件下是否返回True或False。如果你往下看第14行,你可以看到我正在尝试设置我的代码,这样它就会循环并拾取所有以.txt结尾的文件。目录中的每个文件名都不同,所以我试图实现通配符格式。非常感谢你的帮助!

#!/usr/bin/env python
import csv
import json
import pprint
import sys

CSVPATH = 'CsvResults.csv'
VTOUTPUTPATH = './output/'
VTOUTPUTEXT = '.txt'
**vt_result_path = VTOUTPUTPATH + glob.glob('dir/*') + VTOUTPUTEXT**
#vt_result = vt_result_check(vt_result_path)
pp = pprint.PrettyPrinter(indent=4)

# Check files from VirusTotal queries for any positive results
# Result is false unless any nonzero positive result is true
def vt_result_check(vt_result_path):
vt_result = None
try:
vt_result = False
with open(vt_result_path) as vt_result_file:
vt_data = json.load(vt_result_file)
# Look for any positive detected referrer samples
try:
for sample in (vt_data['detected_referrer_samples']):
if (sample['positives'] > 0):
vt_result = True
except:
pass
# Look for any positive detected communicating samples
try:
for sample in (vt_data['detected_communicating_samples']):
if (sample['positives'] > 0):
vt_result = True
except:
pass
# Look for any positive detected downloaded samples
try:
for sample in (vt_data['detected_downloaded_samples']):
if (sample['positives'] > 0):
vt_result = True
except:
pass
# Look for any positive detected URLs
try:
for sample in (vt_data['detected_urls']):
if (sample['positives'] > 0):
vt_result = True
except:
pass
# Look for a Dr. Web category of known infection source
try:
if (vt_data['Dr.Web category'] == "known infection source"):
vt_result = True
except:
pass
# Look for a Forecepoint ThreatSeeker category of elevated exposure
try:
if (vt_data['Forcepoint ThreatSeeker category'] == "elevated exposure"):
vt_result = True
except:
pass
# Look for a Forecepoint ThreatSeeker category of phishing and other frauds
try:
if (vt_data['Forcepoint ThreatSeeker category'] == "phishing and other frauds"):
vt_result = True
except:
pass
# Look for a Forecepoint ThreatSeeker category of suspicious content
try:
if (vt_data['Forcepoint ThreatSeeker category'] == "suspicious content"):
vt_result = True
except:
pass
#pp.pprint(vt_data)
except:
pass
return vt_result

def cert_check(csvpath):
with open(csvpath, 'w') as csvfile:
fieldnames = ['vt_result']
writer = csv.writer(csvfile)
writer.writerow(['VirusTotal Results'])
vt_result_path = VTOUTPUTPATH + subject_dom + VTOUTPUTEXT
vt_result = vt_result_check(vt_result_path)
writer.writerow([vt_result])

您可以使用os.listdir(directoryname)来获取目录中的文件名列表,并且您可以通过使用字符串切片和列表理解来过滤该列表中扩展名为".txt"的文件。例如:

files_to_search = [f for f in os.listdir(directoryname) if f[-4:] == '.txt']

将返回以".txt"结尾的文件名列表(假设所有文件名至少有四个字符长(。

最新更新