python控制台输出转为txt文本

1. 输出到文件print函数
print函数除了打印到控制台,同时还提供了输出到文件的功能,其默认输出文件是sys.stdout,意味着控制台输出

f = open('log.txt','w')
for i in range(100):
    print(str(i), file=f)
f.close()

2. 输出到文件 I/O
将信息输出到文件最直接的方法是使用文件I/O:

f = open('log.txt','w')
for i in range(100):
    f.write(str(i)+'\n')
f.close()

猜你喜欢

转载自blog.csdn.net/weixin_44145452/article/details/109243890