« 拡張子のないファイルをtext/htmlにする |Main| Pythonで「お気に入れっと」 »

« | Python | Pythonで「お気に入れっと」 »

Pythonで特定条件のファイルを検索

後輩の質問に答えたついでにエントリーとして公開します。 「指定したフォルダ以下で最後の3文字が".py"であるようなファイルを探す」という程度のスクリプトなら数行で書けます。

import os
for (root, dirs, files) in os.walk(r"c:\home\Projects"):
	for f in files:
		if f[-3:] == ".py":
			print f, root

これを利用して、「特定のフォルダ以下にある全部のresult.txtを、"そのフォルダの名前.txt"という名前でresultFilesというフォルダにコピー」というスクリプトを作ると以下のようになります。

import os, shutil
for (root, dirs, files) in os.walk(r"."):
    print root
    for f in files:
	if f == "result.txt":
            folderName = os.path.split(root)[-1]
            shutil.copy(
                os.path.join(root, f),
                os.path.join("resultFiles", "%s.txt" % folderName))

print "ok."			

トラックバック(Trackback)

Trackback URL: http://www.nishiohirokazu.org/mt/mt-tb.cgi/16

ご意見・ご感想をお送りください(フィードバック)

(フィードバックはメールで送信され、基本的に表示されませんが、内容によっては公開させていただくこともございます。ご了承ください。Your comment doesn't appear the page immediately. If the comment has value to other people, it will be put on the page or subsequent entries. Thank you.)

上の情報は、いずれも未記入でかまいません。 All of above questions are optional.