python实用工具

列举一些文件操作,配置读取等操作方法。

文件操作

Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
'+'       open a disk file for updating (reading and writing)
'U'       universal newline mode (deprecated)

目录遍历

遍历目录主要有两个方法os.listdiros.walkos.listdir简单遍历指定目录,os.walk会递归遍历所有目录。

# 第一种方法:os.listdir
path = r'E:\books'
for name in os.listdir(path):
    if os.path.isfile(os.path.join(path,name)):
        if name.endswith('.py'):
            # do your job
# 第二种方法:os.walk
for path,dirs,files in os.walk(r'E:\光盘'):
    # do your job
    print(path)

配置

读取常见.ini格式的配置文件,比如如下文件。

[config]
# 地区id (不知道怎么获取的使用一下AreaTool.py工具)
server = 100
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('config.ini')
cfg.getint('config','server')

日志

import logging
logging.basicConfig(level=logging.INFO,format='%(asctime)s:%(pathname)s[line:%(lineno)d]:%(message)s')

https://www.cnblogs.com/nancyzhu/p/8551506.html

Updated: