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

Time:12-31

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:

Abcdefg
Gkfdjawsfd
fasfjk

Result:

fasfjk

CodePudding user response:

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

  • Related