2016年9月14日水曜日

開発環境

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 14.(Files)のExercises 14-1.(No. 3375)を取り組んでみる。

Exercises 14-1.(No. 3375)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys


def sed(old, new, read_filename, write_filename):
    try:
        with open(read_filename) as in_fh, \
                open(write_filename, 'w') as out_fh:
            for line in in_fh:
                line = line.replace(old, new)
                print(line, file=out_fh, end='')
    except Exception as err:
        print(err)
        sys.exit(1)

if __name__ == '__main__':
    print('open -> OPEN')
    sed('open', 'OPEN', 'sample1.py', 'replaced1.txt')
    print('line -> LINE')
    sed('line', 'LINE', 'abcde', 'replaced2.txt')

入出力結果(Terminal, IPython)

$ ./sample1.py
open -> OPEN
line -> LINE
[Errno 2] No such file or directory: 'abcde'
$ cat replaced1.txt 
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys


def sed(old, new, read_filename, write_filename):
    try:
        with OPEN(read_filename) as in_fh, \
                OPEN(write_filename, 'w') as out_fh:
            for line in in_fh:
                line = line.replace(old, new)
                print(line, file=out_fh, end='')
    except Exception as err:
        print(err)
        sys.exit(1)

if __name__ == '__main__':
    print('OPEN -> OPEN')
    sed('OPEN', 'OPEN', 'sample1.py', 'replaced1.txt')
    print('line -> LINE')
    sed('line', 'LINE', 'abcde', 'replaced2.txt')
$ cat replaced2.txt 
cat: replaced2.txt: No such file or directory
$ 

0 コメント:

コメントを投稿

Comments on Google+: