以遍历路径并选择所有xml文件进行操作为例
使用os模块,os.walk、os.path.join等方法
import os
import re
import hashlib
def main():
houzhui = [".xml"]
rootPath = 'Y:/a/b/c/d'
for root, dirs, files in os.walk(rootPath):
for filename in files:
xml_path = os.path.join(root, filename)
ext = os.path.splitext(xml_path)[1]
if ext in houzhui:
print(xml_path)
with open(xml_path, "r", encoding='utf8') as f:
xmltext = f.read()
contents = xmltext.encode(encoding="utf8")
xmlmd5 = hashlib.md5(contents).hexdigest()
insertsql = 'insert into tablename (id,xmlmd5) VALUES ("%s","%s");'%(filename,xmlmd5)