with open(file,'rt',encoding='utf-8',newline='',errors='replace') as f:
    ...

rt模式下,python在读取文本时会自动把rn转换成n.

如果不希望python读取文件时处理其他换行符为n,添加 newline=''参数。

如果读取文件中有编码错误,可以使用errors=replace(在错误的地方插入"?")或ignore处理,但是这些不可逆,python还提供 surrogateescape的可逆方式,具体看链接。stackoverflow_ingore reading a file error

python -u

python 重定向后,会默认启用输出缓冲区,直到程序结束或者缓冲区满才会打印内容。

python -u 关闭缓冲区 立刻输出。

nohup python -u 1.py 1>2.log 2>&1 &

pip 源

# 清华源
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

# 或:
# 阿里源
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
# 腾讯源
pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple
# 豆瓣源
pip config set global.index-url http://pypi.douban.com/simple/

多进程写文件

from multiprocessing import Pool


def setcallback(line):
    with open('result.txt', 'a+') as f:
        f.write(line + '\n')


def run(num):
    return str(num * 2)


pool = Pool(processes=6)
for i in range(10):
    pool.apply_async(func=run, args=(i,), callback=setcallback)
pool.close()
pool.join()

文件结果:

0
4
2
6
8
12
10
14
16
18

End

本文标题:python cookbook

本文链接:https://www.tzer.top/archives/363.html

除非另有说明,本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

声明:转载请注明文章来源。

最后修改:2022 年 04 月 20 日
如果觉得我的文章对你有用,请随意赞赏