python 写入txt的新方法

最新发现有新方法可以对txt等进行操作,比较有意思,之前没见过,故记录下

传统方法

with open(ur'D:\Desktop\a123.txt', 'a') as f: #以写的方式打开
    f.write("Hello world" + str(11))  # 用write不能输入数字要先str函数转换为字符串或者格式化("%d\n" % i)

  

新方法:主要区别就是——用print往文件描述符里写内容,可以输入数字

with open(ur'D:\Desktop\a123.txt', 'a') as f: #以写的方式打开
    print >> f, "Hello world, I'm writting to file", 11  # 用print往文件描述符里写内容,可以输入数字

  

还有:

print >> sys.stderr, "Hello world, I'm writting to file", 11  # 向标准错误输入内容

 

posted on 2018-09-16 14:54  vhills  阅读(422)  评论(0编辑  收藏  举报