python 格式化输出与保存

格式化输出

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() MethodPython 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文件中

方案优劣对比

  1. 方案一在bash终端跑代码时也能看到输出,但需要额外增加代码。
  2. 方案二无需增加代码,但是在bash终端看不到输出,只能自行打开a.txt查看。
  3. 方案三文件路径从项目根目录开始构造。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值