Created
January 14, 2015 09:18
-
-
Save shun91/ff7b7e45b6efbe4ce587 to your computer and use it in GitHub Desktop.
テキストファイルの全ての行に共通の置換処理を行う.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python | |
# -*- coding: utf-8 -*- | |
############################################################ | |
# | |
# テキストファイルの全ての行に共通の置換処理を行うスクリプト. | |
# | |
# 使い方: | |
# ・19,22行目付近の「置換対象の文字列」「置換後の文字列」を設定. | |
# ・下記コマンドで実行. | |
# python all_line_replace.py (input_file) | |
# ・出力ファイル名は「input_file.replace.txt」 | |
# | |
############################################################ | |
import argparse | |
import os | |
# 置換対象の文字列 | |
SEARCH_STRING = ' 1000 1 ' | |
# 置換後の文字列 | |
REPLACE_STRING = ' 1000 2 ' | |
def exec_argparse(): | |
''' | |
引数をパースした結果を連想配列で返す. | |
input_file : 入力ファイルパス | |
''' | |
parser = argparse.ArgumentParser(description='') | |
parser.add_argument('input_file', help='入力するcsvファイル') | |
return parser.parse_args() | |
def replace(input_file): | |
''' | |
テキストファイルの全ての行に共通の置換処理を行う. | |
''' | |
# 出力ファイル | |
output_file = input_file + ".replace.txt" | |
# 出力ファイルの初期化(削除) | |
if os.path.exists(output_file): | |
os.remove(output_file) | |
# 出力ファイルをオープン | |
f_output_file = open(output_file, "a") | |
# 入力ファイルを開く | |
f_input_file = open(input_file, 'r') | |
# 1行ずつ処理. | |
for line in f_input_file: | |
# から始まる行は無視 | |
if line.startswith('#'): | |
continue | |
# relevanceを2に置換して出力ファイルに書き込み | |
line = line.replace(SEARCH_STRING, REPLACE_STRING) | |
f_output_file.write(line) | |
f_input_file.close() | |
f_output_file.close() | |
if __name__ == "__main__": | |
# 引数をパースしてargsに格納 | |
args = exec_argparse() | |
# 置換 | |
replace(args.input_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment