This article describes how to obtain vendor information of all files in a specified folder in batches using python. it is a very practical technique and involves file read/write and dictionary operations, for more information about how to obtain the vendor information of all files in a specified folder in python, see the following example. Share it with you for your reference. The details are as follows:
The function code is as follows:
Import OS, string, shutil, re import pefile import codecs, sys import wx import struct # print Unicode characters in the output # sys. stdout = codecs. lookup ('utf-8') [-1] (sys. stdout) def addToDict (theDict, PEfile_Path, strCompanyName): theDict. setdefault (PEfile_Path, []). append (strCompanyName) # adds the list to the list if it exists. if it does not exist, a new dictionary key def IsPeFile (inputFileName) is created ): ''' determine whether a file is a PE file ''' 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 # obtain the vendor information of a file # Input: file path # output: Dictionary 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) # write the file return dictCompany # obtain vendor information for all files in the folder # input: folder path # output: Dictionary 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"): "write a dictionary to a file" 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') failed t UnicodeEncodeError, e: pass fileOutput. write ("\ n") fileOutput. close () # main function if _ name _ = "_ main _": getCompanyNameFromDir (u "D :\\ everydaySample \ 1221 \ 10 white ") print "OK finish"
The code is very simple.
The following problems occur:
1. write Chinese characters. str. encode ('gb2212 ')
2. the UnicodeEncodeError occurs and the try is used to ignore it.
I hope this article will help you with Python programming.