我必须清除一个txt文件(test.txt),删除以'('或空行开头的行,然后重命名它(test_ok.txt)
我使用这个功能:
def clearfile(filename):
for row in (open (filename, 'r')).readlines():
if row[0][0]<>'\n' and riga[0][0]<>'(' :
out_file = open('%s_%s%s' %(os.path.splitext(filename)[0],'ok',os.path.splitext(os.path.basename(filename))[1]) , 'a')
out_file.write(riga)
out_file.close()
return out_file
它可以工作,但速度很慢。有什么优化技巧吗?
这是我的新功能:
def clearfile(filename):
with open (filename, 'r') as a, open('%s_%s%s' %(os.path.splitext(filename)[0],'ok',os.path.splitext(os.path.basename(filename))[1]) , 'a') as b:
for row in (a).readlines():
if row[0][0]!='\n' and row[0][0]!= '(' :
b.write(row)
b.close