Python:这个代码在替换其内容时是否可以写入我的文件?

时间:2015-02-10 05:16:26

标签: python io

我有一个类似这样的输入文件:

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()

2 个答案:

答案 0 :(得分:0)

当您打开文件时,r+会告诉Python附加到该文件。听起来你想要覆盖文件。 w+标记会为您执行此操作,请参阅Python docs on open()

  

模式'r +','w +'和'a +'打开文件进行更新(读写);请注意'w +'会截断文件。

f = open ('testLC31.txt', 'w+')
def after_semi(f):
    for line in f:
        yield line.split(';')[0]       

for line in after_semi(f):
    f.write('!\n' + line)  

f.close()

我建议使用with来确保文件始终关闭,这应该指向正确的方向:

with open ('testLC31.txt', 'w+') as fout:
    for line in after_semi(f):
        fout.write('!\n' + line) 

希望它有所帮助!

答案 1 :(得分:0)

我会使用下面的re.sub

import re
f = open('file', 'r')                 # Opens the file for reading
fil = f.read()                        # Read the entire data and store it in a variabl.
f.close()                             # Close the corresponding file
w = open('file', 'w')                 # Opens the file for wrting
w.write(re.sub(r';.*', r'', fil))     # Replaces all the chars from `;` upto the last with empty string.
w.close()