Overwrite the file giving only last few words in python

Advertisements

I am trying to write data to a text file in Python using the ‘a’ mode. I changed the mode to ‘w’ to overwrite the existing content of the existing file, but generated file only contains the last few words instead of the entire string file .“

Here’s the code I am using:

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)

Example data to write :

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.

But it is returning only last few words

In some languages, multiple speakers are available.

What could be causing this behavior and how can I fix it?

>Solution :

If you use 'w' write mode, every time you open the file, the content will be overwritten. Since you are opening the file (and closing) on each iteration in your loop, the file gets overwritten every time.
Hence, only your last segment will be visible.
You can use 'a' append mode to avoid overwriting, but since you mention you want to overwrite, I will assume that you want to overwrite the content of the file (before the loop).
To do that, you just need to open the file before the loop:

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

Leave a ReplyCancel reply