【python3】print内容输出到文件

2019-01-08  本文已影响57人  caokai001

使用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)

使用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("C:/Users/16926/Desktop/caokai/compartment")   
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
上一篇 下一篇

猜你喜欢

热点阅读