gpt4 book ai didi

python - 从文本文件中过滤行

转载 作者:太空宇宙 更新时间:2023-11-04 07:42:30 24 4
gpt4 key购买 nike

我必须清除一个 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

最佳答案

为什么多次打开/关闭文件?

def clearfile(filename):
out_file = open('%s_%s%s' %(os.path.splitext(filename)[0], 'ok', os.path.splitext(os.path.basename(filename))[1]) , 'a')
for row in (open (filename, 'r')).readlines():
if row[0][0]!= '\n' and riga[0][0]!='(' :
out_file.write(riga)
out_file.close()
return out_file

关于python - 从文本文件中过滤行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com