python3中print输出到log文件

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文件)