# 複数ファイルを処理する ## 準備(ファイルの確認) ```python !cat lowercase.py ``` ```python # Make the contents of the given file lowercase and output to standard output import sys # Error handling if not sys.argv[1]: raise 'Not enough command line arguments' input_file = sys.argv[1] with open(input_file) as f: for line in f: print(line.strip().lower()) ``` ```python !cat sentences1.txt ``` How have you been ? Pretty good . ```python !cat sentences2.txt ``` I have a pen . We are happy . ## 普通に一つずつファイルを処理する ### 標準出力 ```python # lowercase.py (lowercaseにするpythonスクリプト) で sentences1.txt をlowercase化 # 単に print() で出力していて、下に表示される。これが標準出力 !python lowercase.py sentences1.txt ``` how have you been ? pretty good . ### 標準出力のリダイレクト ```python # 標準出力は > を使うことで別ファイルに"リダイレクト"することができる # これで out.txt というファイルが新しく生成され(あるいは上書きされ)、標準出力が書き込まれる !python lowercase.py sentences1.txt > out.txt ``` ```python # cat で出力されたファイルの中身を確認 !cat out.txt ``` how have you been ? pretty good . ```python # out.txt を削除しておく !rm out.txt ``` ## ループ処理によって複数のファイルを処理する ### ループ処理 ```python # .txtで終わるファイル名を列挙 !for f in *.txt; do echo $f; done ``` sentences1.txt sentences2.txt #### ★説明 ``` for f in *.txt; do echo $f; done ``` は ``` for f in *.txt; do echo $f done ``` と同様。 `*` が正規表現で言う `.*` と同じ意味。ワイルドカード。 一時変数 `f` に `なんとか.txt` が入り、それぞれに対して echo (文字列をそのまま返す)している。 ### ループ処理でpythonスクリプトを動かす ```python # ${f%.txt} で、変数 f の内、末尾の .txt を除く部分を取ってきて、.lower を追加している # なんとか.txt をlowercaseにしたものを なんとか.lower というファイルに出力 !for f in *.txt; do python lowercase.py $f > ${f%.txt}.lower; done ``` ```python # 新しく作成されたファイルの確認 !echo --sentences1.lower-- !cat sentences1.lower !echo --sentences2.lower-- !cat sentences2.lower ``` --sentences1.lower-- how have you been ? pretty good . --sentences2.lower-- i have a pen . we are happy .