Python:这段代码有什么方法可以在替换文件内容的同时写入我的文件吗?

Python: is there any way this code can write to my file while replacing its contents?

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

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

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file.

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) 

希望对您有所帮助!

我会像下面那样使用 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()