You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历目录下文本文件并提取ip、port等指定字段

解决方案

可以通过修改文件读取逻辑,筛选出目标行来实现需求。以下是优化后的代码:

import os

target_keys = {"ip", "port", "uname", "password"}
path = "C:/Users/directory"

def extract_target_lines(file_path):
    target_content = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped_line = line.strip()
            # 跳过空行
            if not stripped_line:
                continue
            # 拆分键和值,判断是否在目标列表中
            key = stripped_line.split('=')[0]
            if key in target_keys:
                target_content.append(stripped_line)
    # 输出当前文件的提取结果
    print(f"--- 来自文件 {os.path.basename(file_path)} 的内容 ---")
    print('\n'.join(target_content))
    print()

# 遍历目录下的txt文件
for file_name in os.listdir(path):
    if file_name.endswith(".txt"):
        file_path = os.path.join(path, file_name)
        extract_target_lines(file_path)

代码说明:

  • 定义target_keys集合存储需要提取的关键字,实现快速判断
  • extract_target_lines函数负责处理单个文件:
    • 逐行读取文件,自动跳过空行
    • 拆分每行的键名,判断是否属于目标关键字范围
    • 收集符合条件的行并按文件分组打印
  • 使用os.path.join拼接文件路径,避免Windows系统下的路径转义问题
  • 移除了不必要的os.chdir操作,避免改变当前工作目录

扩展说明:

如果需要将提取的内容保存到新文件中,可修改extract_target_lines函数,在收集完内容后添加写入逻辑:

output_file = f"extracted_{os.path.basename(file_path)}"
with open(output_file, 'w', encoding='utf-8') as out_f:
    out_f.write('\n'.join(target_content))

内容的提问来源于stack exchange,提问作者Dummy Dumb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:52:12