python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息
更新時間:2014年09月28日 11:51:08 投稿:shichen2014
這篇文章主要介紹了python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息的方法,是非常實用的技巧,涉及到文件的讀寫與字典的操作等技巧,需要的朋友可以參考下
本文實例講述了python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息的方法。分享給大家供大家參考。具體如下:
功能代碼如下:
import os, string, shutil,re
import pefile
import codecs, sys
import wx
import struct
#輸出中打印Unicode字符
#sys.stdout = codecs.lookup('utf-8')[-1](sys.stdout)
def addToDict(theDict,PEfile_Path,strCompanyName):
theDict.setdefault(PEfile_Path, [ ]).append(strCompanyName)
#存在就在基礎上加入列表,不存在就新建個字典key
def IsPeFile(inputFileName):
'''''判斷一個文件是否為PE文件'''
file = open(inputFileName, 'r')
dosSign = hex(struct.unpack("h",file.read(2))[0])
if (dosSign == "0x5a4d"):
file.seek(0x3c)
date_fNew = struct.unpack("l",file.read(4))[0]
file.seek(date_fNew)
peSign = hex(struct.unpack("h",file.read(2))[0])
if (peSign == "0x4550"):
return 1
else:
return 0
else:
return 0
#得到一個文件的廠商信息
#輸入:文件路徑
#輸出:字典
def getCompanyName(PEfile_Path):
if not IsPeFile(PEfile_Path):
return {}
else:
dictCompany = {}
pe = pefile.PE(PEfile_Path)
p = re.compile('''''CompanyName:(.+)''')
for name in p.findall(pe.__str__()):
uniCompanyName = name.replace('\\x', '\\u').strip()
#strTemp = uniCompanyName.decode('unicode_escape')
addToDict(dictCompany, PEfile_Path, uniCompanyName)
writeDicToFile(dictCompany) #寫入文件
return dictCompany
#得到文件夾中所有文件的廠商信息
#輸入:文件夾路徑
#輸出:字典
def getCompanyNameFromDir(dir, dir_callback=None, file_callback=None):
dictAll = {}
for root, dirs, files in os.walk(dir):
for f in files:
file_path = os.path.join(root, f)
if file_callback: file_callback(file_path)
dictAll.update(getCompanyName(file_path))
return dictAll
def writeDicToFile(dicName, outputFileName="company.txt"):
"""將字典寫入文件中"""
fileOutput = open(outputFileName, "a+")
for key, value in dicName.items():
strTemp2 = '' + value[0]
strChina2 = strTemp2.decode('unicode_escape')
try:
fileOutput.write("%-*s" % (110, key))
fileOutput.write(strChina2.encode('gb2312'))
except UnicodeEncodeError, e:
pass
fileOutput.write("\n")
fileOutput.close()
#主函數(shù)
if __name__ == "__main__":
getCompanyNameFromDir(u"D:\\everydaySample\\1221\\10white")
print "ok finish"
這里不解釋,代碼很簡單.
出現(xiàn)的問題如下:
1. 寫入中文.str.encode('gb2212')解決
2. 出現(xiàn)UnicodeEncodeError 的錯誤,用了try給忽略了
希望本文所述對大家的Python程序設計有所幫助。
相關文章
PyTorch上實現(xiàn)卷積神經(jīng)網(wǎng)絡CNN的方法
本篇文章主要介紹了PyTorch上實現(xiàn)卷積神經(jīng)網(wǎng)絡CNN的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
Python數(shù)據(jù)結(jié)構(gòu)與算法中的棧詳解(1)
這篇文章主要為大家詳細介紹了Python中的棧,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-03-03

