格式化输出
str.format
的使用
# 保留小数点后两位
print('price is {:.2f} RMB'.format(49))
# price is 49.00 RMB
# 保存2位小数点的list
a = [0.5013333559036255, 0.7313334345817566]
print('a: {}'.format([float('{:.2f}'.format(i)) for i in a]))
# a: [0.50, 0.73]
# 占3个字节,左对齐
print('price is {:<3} RMB'.format(49))
# price is 49 RMB
# 格式化输出参数多时,使用标签对应输出:apple、price标签
print('{apple:<2} apples with price is {price:.2f} RMB'.format(apple=5, price=49))
# 5 apples with price is 49.00 RMB
# 类似地,使用数字标签:0、1
print('{0:<2} apples with price is {1:.2f} RMB'.format(5, 49))
# 5 apples with price is 49.00 RMB
# 或者直接删除标签,默认顺序对应
print('{:<2} apples with price is {:.2f} RMB'.format(5, 49))
# 5 apples with price is 49.00 RMB
更多参考:Python String format() Method,Python format 格式化函数
保存
方案一:构造类
代码中插入以下类Logger
之后的print
输出都会自动保存到sys.stdout = Logger('a.txt')
中的a.txt
中
import sys
import os
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger('a.txt')
path = os.path.abspath(os.path.dirname(__file__))
type = sys.getfilesystemencoding()
print(path)
print(os.path.dirname(__file__))
# 结果保存在a.txt中了
方案二:终端命令行
bash
终端执行python
是增加> a.txt
python xxx.py > a.txt
方案三:logging包
import logging # 导入logging包
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(filename)s] => %(message)s", # 输出的格式:时间 文件名 => 输出内容
handlers=[
logging.FileHandler(filename="a.log"), # filename=保存的文件, 文件路径从项目根目录开始构造
logging.StreamHandler(sys.stdout), # 在控制面板输出
],
)
# 使用——1
logging.info("{}: {}".format(a, 1)) # 输出:2022-10-06 12:12:24,378 [<string>] => a: 1;同时保存到xxx.log文件中
# 上述例子中`<string>`表示该输出调用的是python内置包文件string.py。
# 使用——2
# 在temp.py中写函数(同时包含logging对象的构造代码)
def a():
logging.info('price is {:.2f} RMB'.format(49))
a() # 输出:2022-10-06 12:15:52,371 [temp.py] => price is 49.00 RMB;同时保存到xxx.log文件中
方案优劣对比:
- 方案一在
bash
终端跑代码时也能看到输出,但需要额外增加代码。 - 方案二无需增加代码,但是在
bash
终端看不到输出,只能自行打开a.txt
查看。 - 方案三文件路径从项目根目录开始构造。