python中write内容为在文件中显示的问题

来源:互联网 发布:淘宝怎么提升信誉 编辑:程序博客网 时间:2024/05/17 22:21

想将一个txt文件中的文本转换下格式,从test_input.txt转移到test1.txt中,使用write写入,运行程序后test1.txt文本为空,代码如下:

import sys,refrom util import *  #util为自定义模块title=Truef=open(r'test1.txt','w')for block in blocks(open(r'test_input.txt')):    block=re.sub(r'\*(.+?)\*',r'<em>\l</em>',block)    if title:        f.write('hl'+'\n')        f.write(block+'\n')        f.write('</hl>'+'\n')        title=False    else:        f.write('<p>'+'\n')        f.write(block+'\n')        f.write('</p>'+'\n')        f.write('</body></html>'+'\n')

后发现文件对象f有默认缓冲区,显示有2种途径:

1.f=open(r'test1.txt','w',0)  使默认缓冲区为0可直接写入

2.代码最后增加f.flush()或f.close(),一般文件对象最后都需f.close()

0 0
原创粉丝点击