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

Writing string to a file on a new line every time in Python

I have a loop, which have to write text on a new line every time. Here`s the code in Python:

    for j in b:
        data = json.loads(json.dumps(j))
        data = json.dumps(data)
        data = json.loads(data)
        from_id = data['from_id']
        text = data['text']
        if (os.path.exists(f'{user_id}.txt')):
            with open(f'{user_id}.txt', 'w', encoding='utf-8') as file:
                file.write(f'{from_id}: {text}\n')

I tried to use \n at the end, but it doesnt work for me.
As result it just writes the last line of the loop`s text.

Text:

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

Abcdefg
Gkfdjawsfd
fasfjk

Result:

fasfjk

>Solution :

The write mode w writes from the beginning of the file.

When the code is not looped, you just want to append, just append mode a, it would look like :

with open(f'{user_id}.txt', 'a', encoding='utf-8') as file:
    file.write(f'{from_id}: {text}\n')

But here you have a loop and the file isn’t dependent of the loop (user_id is not defined in the loop), so you can just open the file outside the loop once

with open(f'{user_id}.txt', 'w', encoding='utf-8') as file:
    for data in b:
        from_id = data['from_id']
        text = data['text']
        file.write(f'{from_id}: {text}\n')

Also the dumps/loads part seems useless, I removed it

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