python cookbook 学习笔记 第五章 文件与IO (2) 打印输出至文本文件

  • 打印输出至文本文件
  • 问题:
    • 想将print()函数的输出重定向到一个文件中去
  • 解决方案:
    • 在print()函数中指定 file 关键字参数,像下面这样:
with open("d:/work/test.txt", "wt") as f:
    print("hello world!", file= f)
with open(r"E:\test\python进阶\Python_cookbook_第四章\Python_cookbook_第四章(1).py",
          encoding= "utf-8") as f,\
        open("test.txt","wt") as w:
    for line in f:
        print(line, file= w,end="")
  • 讨论: 关于输出重定向到文件中就这些了,文件必须以文本模式打开,如果是二进制模式的话,打印就会出错。

猜你喜欢

转载自blog.csdn.net/qq_43539055/article/details/84889026