1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

複数のファイルから指定の文字列を有するファイルを抽出する

Last updated at Posted at 2023-09-21

備忘録

使いたいときに自分で使う

main.py
# osモジュールをインポート
import os

# ディレクトリのパスを指定
dir_path = r"C:\Users\taizu\Desktop\judge"

word = 'tyogokin' #検出するワード

# os.walk関数でディレクトリ内のファイルを再帰的に探索
num = 0
for root, dirs, files in os.walk(dir_path):
    # ファイルの絶対パスを生成
    for file in files:
        file_path = os.path.join(root, file)
        # 絶対パスを出力
        try:
            with open(file_path, encoding="utf-8") as f:
                s = f.read()
            if str(word) in s :
                num += 1
                print(file_path)
        except :
            pass
print('')
if int(num) == 0 :
    print('検出されませんでした。')
else :
    print(str(num) + '個のファイルで「{}」が検出されました。'.format(str(word)))

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?