たまに追加したりします。
# ! env python
# -*- coding: utf-8 -*-
import os
import sys
import configparser
import glob
import numpy as np
def ini(section, value, path="config.ini", encoding='utf-8'):
"""
iniファイルの内容を返す。
example file
[root]
test=data
example code
print(ini("root","test","config.ini","utf-8"))
:param section:
:type section: str
:param value:
:type value: str
:param path:
:type path: str
:param encoding:
:type encoding: str
:return:
:rtype: str
"""
root = os.path.dirname(os.path.abspath(sys.argv[0]))
config = configparser.ConfigParser()
config.read(os.path.join(root, path), encoding=encoding)
try:
return config.get(section=section, option=value)
except configparser.NoOptionError:
print("iniファイルに%sセクション%sがありませんでした。" % (section, value))
def dir_clear(path):
"""
フォルダの中身を再帰的に削除
:param path:
:type path: str
:return:
"""
for item in os.listdir(path):
tmp = os.path.join(path, item)
if os.path.isdir(tmp):
dir_clear(tmp)
if len(os.listdir(tmp)) > 0:
return
try:
os.rmdir(tmp)
print("removed dir == ", tmp)
except PermissionError:
print("permission error dir == ", tmp)
else:
try:
os.unlink(tmp)
print("removed file == ", tmp)
except PermissionError:
print("permission error file == ", tmp)
def get_files(path, depth=-1, is_hide_file=False):
"""
ファイルだけを再帰的に取得
:param path: フォルダのパス
:type path: str
:param depth: どれだけ深い階層を調べるか。マイナス値で際限ない深さを探す
:type depth: int
:param is_hide_file: 隠しファイルを対象とするか
:type is_hide_file: bool
:return:
:rtype: list
"""
dir_list = []
for item in os.listdir(path): # globは不可視ファイルが見えないのでlistdirを使う
tmp = os.path.join(path, item)
if os.path.isdir(tmp) and depth != 0:
depth = depth - 1
dir_list.extend(get_files(tmp, depth, is_hide_file))
elif not os.path.isdir(tmp):
if os.path.basename(item)[0] == "." and not is_hide_file:
continue
dir_list.append(tmp)
return dir_list
def get_image_files(path, depth=-1):
"""
画像ファイルだけを再帰的に取得
:param path: フォルダのパス
:type path: str
:param depth:どれだけ深い階層を調べるか。マイナス値で際限ない深さを探す
:type depth: int
:return:
:rtype: list
"""
dir_list = []
for item in glob.glob(os.path.join(path, "*")):
if os.path.isdir(item) and depth != 0:
depth = depth - 1
dir_list.extend(get_image_files(item, depth))
elif not os.path.isdir(item):
# ファイルの先頭が.か、拡張子がまったくない場合は除外
if os.path.basename(item[0]) == "." or "." not in item:
continue
# 他の画像ファイルの拡張子を使いたい場合はここを修正
if os.path.splitext(item)[1][1:] in ["jpg", "jpeg", "png", "tif", "tiff", "psd", "eps"]:
dir_list.append(item)
return dir_list
他の人の便利な関数
日本語ファイルパス対応のOpenCVのimread,imwrite
https://qiita.com/SKYS/items/cbde3775e2143cad7455