1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【python】私的作成&利用してる小規模関数(ファイル操作等)

Posted at

小ネタ的な記事ですが…

pythonは色々な操作がやりやすく、また環境変数「PYTHONPATH」へ作成済みモジュールを配置しておけば
再利用が効きやすいため、細かなスクリプトを作るときには便利な言語です

当記事では、私的に作成、利用している関数について
メモ置きついでに紹介します
(ありきたりな物が多いため、既出の物も多いかと思います)

ファイル読み込み/書き込み操作

import codecs
def pfreadlines(filename,encoding=None,**args):
    with codecs.open(filename,Mode="r",encoding=encoding,**args) as f:
        ret = f.readlines()
    return ret

def pfwritelines(data,filename,encoding=None,**args):
    with codecs.open(filename,Mode="w",encoding=encoding,**args) as f:
        f.writelines(data)

上の関数を一つ呼び出せば、ファイルへの書き込み/読み込みができます
状況に応じてread/writeも作って行けば利便性も上がりそうです

複数Replace操作

正規表現での対応も手ですが、そこまでしなくても良い時等に

def replace_all(src,new,*old):
	for i in old:
		src = src.replace(i,new)
	
	return src

引数が本来のreplaceと逆なので混同しそうですが…

対象dictにキーが見つからなかったとき、新たな要素を追加する

def dict_insert(src,key,value=True):
    if(src.get(key) == None):
        src[key] = value

「対象キーが見つからなかった時に~」的な操作が多い時に便利です(でした)

おわりに

「この操作、こう書くことが出来るよ」とか、「このライブラリめっちゃ便利なのでオススメ」といった物がありましたら
是非コメントお願いします。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?