Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overwrite the file giving only last few words in python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading