0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python_Tool_フォルダ内Text文字列の一括抽出

Last updated at Posted at 2025-02-15

textファイルの(A)〜(B)までの文字列を抜き出す

はじめに

この記事は
あるフォルダ(Fフォルダ)の中に入っているtextファイルの文字列(A)〜(B)までを書き出すTooLを作成するものです。

使用例

・NW機器のコマンド出力一覧からあるコマンド結果のみを書き出す
・テキストの一覧から必要部分だけを書き出す。

挙動

例)
Fフォルダ
	└TEST1.log
	└TEST2.log
	└TEST3.log
	└TEST4.log

このToolで全ての.logファイルの
文字列(A)〜(B)までを抜き出して、afterフォルダ内にコピーを作る


Fフォルダ
	└TEST1.log
	└TEST2.log
	└TEST3.log
	└TEST4.log
    	└after
        	└TEST1.log
        	└TEST2.log
        	└TEST3.log
            └TEST4.log
            ※文字列(A)〜(B)までを抽出したファイルが出来る。

準備物

・Python実行環境

・エディタ

1.必要データを確認する

■必要データ
 FフォルダPath   = 例)[ForderPath]
 ファイル拡張子   = ".log"
 開始位置 文字列(A) = [#show run]
 終了位置 文字列(B) = [end]

2.以下コードにデータを入力する

import os

# フォルダの指定
input_folder = r"(FフォルダPath)"
after_folder = os.path.join(input_folder, "after")

# "after"フォルダを作成
os.makedirs(after_folder, exist_ok=True)

# .txtファイルを処理
for file_name in os.listdir(input_folder):
   if file_name.endswith(".log"):
       input_file_path = os.path.join(input_folder, file_name)
       output_file_path = os.path.join(after_folder, file_name)
       print(input_file_path)
       
       with open(input_file_path, "r", encoding="utf-8") as f:
           lines = f.readlines()
           
       
       # "#show run" から "end" までを抽出
       extracting = False
       show_run_cp = []
       for line in lines:
           if "#show run" in line:
               extracting = True
           if extracting:
               show_run_cp.append(line)
           if line.strip() == "end":
               break
       
       # 抽出した内容を新しい.txtに書き込み
       with open(output_file_path, "w", encoding="utf-8") as f:
           f.writelines(show_run_cp)

print("処理が完了しました。")

データを入力したら、Pythonファイルとして保存する、今回は「00_remake.py」とする。

※文字列(A)〜(B)について

詳しくは、lines というリスト内の行を順に処理し、文字列(A)を含む行が見つかったら、その行以降を show_run_cp に追加し、文字列(B) のみの行が出てきたら処理を終了する

 

3.処理の実行

スクリーンショット 2025-02-15 19.40.18.png

00_remake.pyをエディタで開き実行する。

スクリーンショット 2025-02-15 19.42.10.png

afterフォルダが自動作成され、その中に文字列(A)〜(B)のコピーを抽出したTextファイルが作成される。

スクリーンショット 2025-02-15 19.43.11.png

これで完了です!お疲れ様でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?