在平时工作中,有时我们需要将控制台输出保存到文件

1.命令行用>覆盖写入和>>追加写入

python 把输出结果保存为字典 python把结果输出到文件_python

python 把输出结果保存为字典 python把结果输出到文件_python控制台输出到文件_02

for i in range(10000):
print(i)
View Code

#将控制台输出覆盖写入到文件

python myprint.py > myprint.txt

#将控制台输出追加写入到文件

python myprint.py >> myprint.txt

2.将sys.stdout输出到文件

python 把输出结果保存为字典 python把结果输出到文件_python

import sys
import time
f=open("myprint.txt","w+")
sys.stdout=ffor i in range(1000):
print(i*9)
View Code

缺点:只能保存到文件,但控制台无输出

3.利用print函数中的file参数

python 把输出结果保存为字典 python把结果输出到文件_python

python 把输出结果保存为字典 python把结果输出到文件_python控制台输出到文件_02

import sys
import time
f=open("myprint.txt","w+")for i in range(100):
print("--{}--".format(i**2),file=f,flush=True)
print("--{}--".format(i ** 2),file=sys.stdout)
time.sleep(0.5)
View Code

将控制台输出的同时即时保存到文件

print函数中的file参数,file=f,输出到文件;file=sys.stdout,输出到终端;flush=True,即时刷新

4.用类实现

python 把输出结果保存为字典 python把结果输出到文件_python

python 把输出结果保存为字典 python把结果输出到文件_python控制台输出到文件_02

import sysclass Logger(object):
def __init__(self, filename='default.log', stream=sys.stdout):
self.terminal=stream
self.log= open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
sys.stdout= Logger(stream=sys.stdout)
# now it works
print('print something')
print("output")
View Code
iOS 圆角绘制虚线 iphone圆角

在开发中我们经常会遇见设置控件圆角的属性,一般我们有三种处理方式1、使用CALayer-(instancetype)cornerAngel:(CGFloat)angel CALayer* layer=self.layer; layer.cornerRadius=angel; layer.masksToBounds=YES; return self;

python 读取变量类型 python从文本中读取变量值

关于this question,我有一个相似但不相同的问题。。在路上,我会有一些文本文件,结构如下:var_a: 'home' var_b: 'car' var_c: 15.5我需要python读取文件,然后创建一个名为var_a的变量,值为“home”,依此类推。示例:#python stuff over here getVarFromFile(filename) #this is the fu