Python 萌新笔记

⚠️ 本文最后更新于2025年01月27日,已经过了92天没有更新,若内容或图片失效,请留言反馈
  1. pyinstaller 为例:打包成 .exe 文件使用时,不能用 pathlib.Path(__file__) 获取文件路径,要用 sys.argv[0] 获取,不然会出错。
  2. 当字典中 key 存在时,__getitem__,即 dict[key]dict.get(key) 更快;当字典中 key 不存在时,dict.get(key)__getitem__ + try-except 更快
  3. pathlib 库的时候尽量能用就用绝对路径,如果在其他库函数传参传 Path 类报 TypeError 错,大部分情况下传 str(Path) 就能解决
  4. for 套 for 也可以用列表解析式, 同样的写法,写两个 for 就行:

    test = [
     (1, [11, 12, 13, 14]),
     (2, [21, 22, 23, 24]),
     (3, [31, 32, 33, 34]),
    ]
    
    print([
     ...
     for a, b in test
     for c in b
    ])
  5. 读取文件内容后需要先用 IO.seek() 方法将读取指针重置到开头才能再次读取:

    import json
    with open(...) as fp:
     lines = fp.readlines()
     fp.seek(0)
     data = json.load(fp)
  6. windows 系统下文件路径过长也会导致 FileNotFoundError。win+R 运行 gpedit.msc,点开 计算机配置 > 管理模板 > 系统 > 文件系统,找到“启用 Win32 长路径”,将其状态更改为“已启用”即可
By Number_Sir On