美文网首页
python3中print输出到log文件

python3中print输出到log文件

作者: 哪个鹿 | 来源:发表于2019-12-19 18:45 被阅读0次

1. 使用print("string", file="")来实现

with open('./hello','wt') as f: 
    for i in range(4979):
        print("chr{0}\t{1}\t{2}".format(1,i*50000,(i+1)*50000),file=f)

2. 使用sys来实现

import sys
savedStdout = sys.stdout  #保存标准输出流
with open('./hello', 'wt') as file:
    sys.stdout = file  #标准输出重定向至文件
    print('This message is for file!')
    print("chr{0}\t{1}\t{2}".format(1,i*50000,(i+1)*50000))

sys.stdout = savedStdout  #恢复标准输出流
print ('This message is for screen!')

输出大文件前几行(类似R head())

import os        
os.chdir("./test")   
k=50     
with open("85.txt") as f: 
    n=0
    for line in f.readlines():
        n+=1
        print(line.replace("\n",""))
        if n==k:
            break

相关文章

网友评论

      本文标题:python3中print输出到log文件

      本文链接:https://www.haomeiwen.com/subject/dshoectx.html