LoginSignup
10
11

More than 3 years have passed since last update.

PerlっぽいフィルタプログラムをPythonで書きやすくするモジュールfileinput

Last updated at Posted at 2015-01-17

個人的にPerlに惹かれるところってwhile (<>)を使ってフィルタプログラムを簡単に書けるところだと思うんですよね。

#!/usr/bin/perl

while (<>) {
  y/a-z/A-Z/;
  print;
}

これだけで小文字を大文字にするフィルタプログラムが完成。引数で何個でもファイルが指定できるし、無引数なら標準入力から読み込むような挙動になります。

$ echo hoge | ./toupper.pl
HOGE
$ ./toupper.pl hoge.txt hoge2.txt
HOGE
HOGE2
$

実は、fileinputモジュールを使えばPythonでも同じことができます。

#!/usr/bin/python
import fileinput

for line in fileinput.input():
    sys.stdout.write(line.upper())

ファイル名として「-」を指定すると標準入力の意味になるところまで一緒です。

参照:https://docs.python.org/2/library/fileinput.html

10
11
1

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
10
11