LoginSignup
0
9

More than 5 years have passed since last update.

Python覚書2

Last updated at Posted at 2017-01-12

pythonでサクッとツール作ったので、覚書。
ソースは会社とかのあれがあれなので、要所要所を覚え書き

ディレクトリの再帰処理

すべてのファイルを取得するFunction

こちらをとても参考にさせてもらいました。

def get_all_files(directory):
    for path, dirs, files in os.walk(directory):
        for file in files:
            yield os.path.join(path, file)

すべてのディレクトリを取得するFunction

こちらから拝借。

def get_all_files(directory):
    for path, dirs, files in os.walk(directory):
        yield path

すべてのディレクトリとファイルを取得するFunction

こちらから拝借。

def get_all_files(directory):
    for path, dirs, files in os.walk(directory):
        yield path
        for file in files:
            yield os.path.join(path, file)

使う時

for file in get_all_files('/tmp/test'):
    print file

yieldについて

こちらがとても参考に成った。
簡単に言うと、処理の内容をretrunせずにおいておけるものらしい
で、ループで回したり、next()で取得できる。つまり

def test():
    yield 'a'
    yield 'b'
    yield 'c'

for i in test():
    print i

を実行すると

a
b
c

と出力される。

ファイル処理

フルパスからファイル名を取得する

これはよく使う

file_name = os.path.basename(file)

フルパスから拡張子とそれ以外分割する

拡張子を見たかったので

file_title, file_ext = os.path.splitext(file_name)

ファイルをUTF-8で開いて、全行を読み込む

UTF-8で開くときは、unicodeに気をつける必要がある

f = codecs.open(file, 'r', 'utf-8')
list = f.readlines()
f.close()

ファイルをUTF-8で開いて、書き込む

ファイルが存在しない時は作成する。
stringはunicodeであれば日本語でも書き込める。
printするときは、print(string.encode('utf-8'))のようにする。
\nいれないとCRLF改行でひらいたときに改行されない。

result = codecs.open(outfile, 'a', 'utf-8')
result.write(format("string --> %s\n" % string))
result.close()

読み込んだファイルを比較するときは文字コードを統一しないといけなくて
結構ハマった。。。

文字列比較

任意の文字列が含まれるかどうか

line = "1abcdefg23456789"
target_string = "1a"

if (target_string in line):

処理が増えてくると、Pythonでうーん、、と感じることも何回かありましたが
さくっと書くにはPythonはいいですね。好きです。

0
9
2

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
0
9