我有一个类似这样的输入文件:
blah blah
blah blah ;blah blah
blah blah ;blah blah
blah
我的程序所做的是在看到分号时分割行,然后转到下一行,这是我希望它做的(我希望它忽略分号位),产生如下结果:
blah blah
blah blah
blah blah
blah
但是,当它写入文件时,它会将新代码附加到旧代码中,我只想在文件中包含新代码。有什么办法可以做到吗?谢谢您。你知道吗
f = open ('testLC31.txt', 'r+')
def after_semi(f):
for line in f:
yield line.split(';')[0]
for line in after_semi(f):
f.write('!\n' + line)
f.close()
打开文件时,
r+
命令Python附加到文件。听起来你想覆盖这个文件。w+
标志将为您实现这一点,请参见Python docs on open()我建议使用
with
来确保文件总是被关闭,这应该为您指明正确的方向:希望有帮助!你知道吗
我会像下面那样使用
re.sub
相关问题 更多 >
编程相关推荐