python os.path.exists()的正则匹配

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据你的代码,你想将提取的文件名数据加载到一个DataFrame中,并将原有的CSV文件读取到另一个DataFrame中。然后,你可能想将提取的文件名数据写入已建的CSV文件中。以下是你可以继续完善的代码示例: ```python import os from bs4 import BeautifulSoup import re import csv import pandas as pd # 指定文件夹路径 folder_path = "C:/Users/test/Desktop/DIDItest" # 正则表达式模式 pattern = r'<body>(.*?)<\/body>' # 创建CSV文件并写入表头 csv_file = "output.csv" header = ['File Name'] # 表头 # 首次创建CSV文件时,写入表头 if not os.path.exists(csv_file): with open(csv_file, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(header) # 遍历文件夹中的所有文件 for root, dirs, files in os.walk(folder_path): for file in files: # 读取html文件 file_path = os.path.join(root, file) with open(file_path, "r", encoding="utf-8-sig") as f: html_code = f.read() # 创建BeautifulSoup对象 soup = BeautifulSoup(html_code, 'html.parser') # 使用正则表达式匹配<body>标签内的数据 body_data = re.findall(pattern, html_code, re.DOTALL) # 剔除<p>和()</p> body_data = body_data[0].replace("<p>", "").replace("()</p>", "") # 使用正则表达式提取文件名 matches = re.findall(r'"([^"]*)"', body_data) if matches: file_name = matches[0] else: file_name = "No matches found." # 替换字符 file_name = file_name.replace('No matches found.', '') # 将提取的数据写入CSV文件 with open(csv_file, mode='a', newline='') as file: writer = csv.writer(file) writer.writerow([file_name]) print("数据已成功写入CSV文件") ``` 在上面的代码中,我添加了一些逻辑来创建CSV文件并写入表头。然后,使用`csv.writer`将提取的文件名写入CSV文件中的新行。请确保提供正确的文件夹路径和CSV文件路径,并根据需要调整代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值