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

2024-09-24 00:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 文件代码in程序txtfordefline
2条回答

打开文件时,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()

相关问题 更多 >