Skip to content

Python Code Snippets

logging

1
2
3
4
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(filename)s : %(funcName)s : %(message)s', level=logging.DEBUG)
logging.info('xxxxx')
logging.warning('ssss')

structs

1
2
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])

获取脚本地址

1
2
3
import os

APKSEC_DIR = os.path.split(os.path.realpath(__file__))[0]

遍历目录

1
2
3
4
5
for root, dirs, files in os.walk(root_dir) :
    for d in dirs:
        print os.path.join(root, d)
    for f in files:
        print os.path.join(root, f)

遍历一级:

1
2
for each_file in os.listdir(apk_dir):
    print each_file

Python3:

1
found_images = pathlib.Path('/path/').glob('**/*.jpg')

文件复制

1
shutil.copy(xx,yy)

文件移动

1
shutil.move(xx,yy)

分离路径和文件名

1
os.path.split(spath)

计算相对路径

1
2
3
print each_file_path
print self.plugin_task_path
print os.path.relpath(each_file_path, self.plugin_task_path)

结构体

1
2
3
4
5
import collections
Clazz = collections.namedtuple('Clazz',['field1', 'field2'])

# to dict
clazz._asdict()