在 python 中覆盖写入而不是追加

问题描述 投票:0回答:2

我正在尝试使用“a”模式将数据写入 Python 中的文本文件。我将模式更改为'w'以覆盖现有文件的现有内容,但生成的文件仅包含最后几个单词而不是整个字符串文件。``

这是我使用的代码:

for segment in segments:
        startTime = str(0)+str(timedelta(seconds=int(segment['start'])))+',000'
        endTime = str(0)+str(timedelta(seconds=int(segment['end'])))+',000'
        text = segment['text']
        segmentId = segment['id']+1
        segment = f"{segmentId}\n{startTime} --> {endTime}\n{text[1:] if text[0] is ' ' else text}\n\n"
        with open(filepath, 'w', encoding='utf-8') as srtFile:
            srtFile.write(segment)

要写入的示例数据:

Easily convert your US English text into professional speech for free. Perfect for e-learning, presentations, YouTube videos and increasing the accessibility of your website. Our voices pronounce your texts in their own language using a specific accent. Plus, these texts can be downloaded as MP3. In some languages, multiple speakers are available.

但它只返回最后几句话

In some languages, multiple speakers are available.

什么可能导致这种行为,我该如何解决?

python flask file-io text-files
2个回答
0
投票

如果使用

'w'
写模式,每次打开文件,内容都会被覆盖。由于您在循环中的每次迭代中打开(和关闭)文件,因此文件每次都会被覆盖。 因此,只有你的最后一个
segment
是可见的。 您可以使用
'a'
追加模式来避免覆盖,但是由于您提到您 want 覆盖,我假设您想覆盖文件的内容(在循环之前)。 为此,您只需要在循环之前打开文件:

with open(filepath, 'w', encoding='utf-8') as srtFile:
    for segment in segments:
        # Your processing here
        
        # write to the file here
        srtFile.write(segment)

0
投票

简单地,替换:-

with open(filepath, 'a', encoding='utf-8') as srtFile:
    srtFile.append(segment)

您要注意:在

open
中将
'w'
替换为
'a'
write
append

© www.soinside.com 2019 - 2024. All rights reserved.