当前位置: 首页 > news >正文

南充做网站南昌官网seo诊断

南充做网站,南昌官网seo诊断,渭南是哪个省,做网站的属于什么工作类型在处理文件系统时#xff0c;我们经常需要遍历目录结构以查找特定文件或执行某些操作。Python 提供了一个非常有用的函数 os.walk()#xff0c;它可以帮助我们轻松地遍历目录树。本文将详细介绍 os.walk() 的使用#xff0c;并提供一个实际的应用示例。 os.walk() 的基本用…在处理文件系统时我们经常需要遍历目录结构以查找特定文件或执行某些操作。Python 提供了一个非常有用的函数 os.walk()它可以帮助我们轻松地遍历目录树。本文将详细介绍 os.walk() 的使用并提供一个实际的应用示例。 os.walk() 的基本用法 os.walk() 是一个生成器它会递归地遍历目录树中的所有目录和文件。它的基本语法如下 import osfor dirpath, dirnames, filenames in os.walk(your_directory):print(Current Path:, dirpath)print(Directories:, dirnames)print(Files:, filenames)参数说明 dirpath当前遍历的目录路径。dirnames当前目录下的子目录列表。filenames当前目录下的文件列表。 示例 假设我们的目录结构如下 example_dir/ │ ├── subdir1/ │ ├── file1.txt │ └── file2.txt │ ├── subdir2/ │ └── file3.txt │ └── file4.txt我们使用 os.walk() 来遍历这个目录 import osfor dirpath, dirnames, filenames in os.walk(example_dir):print(Current Path:, dirpath)print(Directories:, dirnames)print(Files:, filenames)输出结果将如下所示 Current Path: example_dir Directories: [subdir1, subdir2] Files: [file4.txt]Current Path: example_dir/subdir1 Directories: [] Files: [file1.txt, file2.txt]Current Path: example_dir/subdir2 Directories: [] Files: [file3.txt]可以看到os.walk() 递归地遍历了 example_dir 目录中的所有子目录和文件。 实际应用示例同步文件到 MongoDB 我们通过一个实际的示例来展示 os.walk() 的应用。假设我们需要同步一个目录中的 PDF 和 XML 文件到 MongoDB并且 XML 文件和对应的 PDF 文件在同一个目录中但名称不一定相同。我们可以使用 os.walk() 来遍历目录并找到每个 XML 文件对应的 PDF 文件。 完整代码示例 import logging import os import re from logging import handlers from datetime import datetime import xml.etree.ElementTree as ET from pymongo import MongoClient, errors import gridfs# 用户输入部分 sync_file_path sync_mongo_url sync_mongo_username sync_mongo_password sync_mongo_db sync_mongo_collection if sync_file_path :sync_file_path rD:\WG\202304 if sync_mongo_db :sync_mongo_db FMSQ if sync_mongo_collection :sync_mongo_collection test if sync_mongo_url :sync_mongo_url 192.168.0.234:27017 if sync_mongo_username :sync_mongo_username admin if sync_mongo_password :sync_mongo_password 123456# 日志文件配置 log_dir f./log/sync_pdf_xml_to_mongo_0001/{sync_mongo_db}-{sync_mongo_collection} if not os.path.exists(log_dir):os.makedirs(log_dir)class Logger(object):level_relations {debug: logging.DEBUG,info: logging.INFO,warning: logging.WARNING,error: logging.ERROR,crit: logging.CRITICAL}def __init__(self, filename, levelinfo, whenD, back_count3,fmt%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s):self.logger logging.getLogger(filename)format_str logging.Formatter(fmt)self.logger.setLevel(self.level_relations.get(level))sh logging.StreamHandler()sh.setFormatter(format_str)th handlers.TimedRotatingFileHandler(filenamefilename, whenwhen, backupCountback_count, encodingutf-8)th.setFormatter(format_str)self.logger.addHandler(sh)self.logger.addHandler(th)log_all_path f{log_dir}/sync_pdf_to_mongo_all.log log_error_path f{log_dir}/sync_pdf_to_mongo_error.log log Logger(log_all_path, leveldebug) error_log Logger(log_error_path, levelerror)def find_pdf_file(xml_file_path, files):directory os.path.dirname(xml_file_path)for file in files:if file.endswith(.PDF):return os.path.join(directory, file)return Nonedef upload_files():log.logger.info(fSync directory path: {sync_file_path})log.logger.info(fMongoDB URL: {sync_mongo_url})log.logger.info(fMongoDB username: {sync_mongo_username})log.logger.info(fMongoDB password: {sync_mongo_password})log.logger.info(fMongoDB database: {sync_mongo_db})log.logger.info(fMongoDB collection: {sync_mongo_collection})# MongoDB 连接client MongoClient(fmongodb://{sync_mongo_username}:{sync_mongo_password}{sync_mongo_url}/?retryWritestruewmajority,serverSelectionTimeoutMS5000)db client[sync_mongo_db]fs gridfs.GridFS(db)for root, dirs, files in os.walk(sync_file_path):for file in files:if file.endswith(.XML):xml_file_path os.path.join(root, file)pdf_file_path find_pdf_file(xml_file_path, files)if not pdf_file_path:error_log.logger.error(fPDF file not found for XML: {xml_file_path})continuetry:tree ET.parse(xml_file_path)root_element tree.getroot()doc_number_match re.search(rdocNumber([\s\S]*?), ET.tostring(root_element, encodingutf-8).decode(utf-8))if not doc_number_match:error_log.logger.error(fdocNumber not found in XML: {xml_file_path})continuedoc_number doc_number_match.group(1)new_pdf_filename f{doc_number}.PDFnew_pdf_file_path os.path.join(root, new_pdf_filename)os.rename(pdf_file_path, new_pdf_file_path)log.logger.info(fRenamed {pdf_file_path} to {new_pdf_file_path})query {filename: new_pdf_filename}log.logger.info(f{new_pdf_filename} uploaded to MongoDB.)if fs.exists(query):log.logger.info(f{new_pdf_filename} already exists in MongoDB.)else:with open(new_pdf_file_path, rb) as pdf_file:content pdf_file.read()fs.put(content, filenamenew_pdf_filename, upload_timedatetime.now())log.logger.info(f{new_pdf_filename} uploaded to MongoDB.)except (errors.ServerSelectionTimeoutError, errors.AutoReconnect) as conn_error:error_log.logger.error(fError connecting to MongoDB while processing XML: {xml_file_path}: {conn_error})except Exception as e:error_log.logger.error(fError processing XML file: {xml_file_path}: {e})log.logger.info(All files processed.)upload_files()在这个示例中我们使用 os.walk() 递归地遍历指定目录中的所有文件和子目录并对每个 XML 文件执行以下操作 查找同目录中的 PDF 文件。解析 XML 文件以提取 docNumber。重命名 PDF 文件并将其上传到 MongoDB。 通过这种方式我们能够有效地处理目录中的所有文件并确保每个 XML 文件都有对应的 PDF 文件。
http://www.zqtcl.cn/news/421980/

相关文章:

  • 网站未备案什么意思网站 php .net
  • 网站开发第三方登录设计七牛图床 wordpress
  • 大连网站设计案例宁波品牌网站设计价格
  • 响应式表白网站源码黑龙江建设网电话
  • wordpress企业建站生产企业做网站的费用怎么做账
  • 天都城网站建设wordpress pluings
  • 惠州做网站的公司有哪些wordpress主动推送
  • jsp做的网站带数据库新手网站设计定价
  • 做网站公司需要什么条件不锈钢公司网站源码 网站建设 产品3级分类asp源码
  • 经营网站挣钱网络运维工程师证书怎么考
  • 厦门网站建设ui株洲企业网站制作
  • 创建个网站需要多少钱张家界seo优化方案
  • 深圳营销型网站建设公司哪家好熊岳网站怎么做
  • 邢台企业网站建设好么找公司做网站要注意什么问题
  • 做博客网站要怎么配置的服烟台app开发公司
  • 从化网站建设方案怎么注册公司名字
  • 网站建设需要哪些书籍免费做游戏网站
  • 杭州 网站定制做旅游网站宣传
  • 泉州市做网站优化建设地情网站的作用
  • 筑巢网络官方网站打开搜索引擎
  • 赣州做网站公司哪家好网站先做前端还是后台
  • wordpress关闭网站吗用织梦做的学校网站
  • 响应式网站建设平台东莞网站建设aj
  • 代码做网站的软件市场营销策划书
  • 东莞网站建设 手机壳文登建设局网站
  • 网站建设和后台空间管理关系企业网络需求分析
  • 做小说网站做国外域名还是国内的好温州市网站建设
  • wordpress识别手机跳转网站3d视频动画制作
  • 展示型企业网站设计方案邯郸市口碑网络技术有限公司
  • 网站配色案例泰州seo平台