常用 Python 代码片段

# 网络

"""
请求头
"""
headers = {
    "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.6) ",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "en-us",
    "Connection": "keep-alive",
    "Accept-Charset": "GB2312,utf-8;q=0.7,*;q=0.7"
}
1
2
3
4
5
6
7
8
9
10

# 文件

def tranverse(dir: str):
    """
    遍历给定文件夹,并返回所有文件(不含文件夹)路径组成的数组
    """
    ret = []
    for root, dirs, files in os.walk(dir):
        for file in files:
            ret.append(os.path.join(root, file))
    return ret


def md5_file(file: str) -> str:
    """
    计算给定文件的 md5
    """
    with open(file, 'rb') as file:
        return hashlib.md5(file.read()).hexdigest()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17