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

Python Issue writing txt file

I’m trying to write element I parsered with beautifulsoup in python to a txt file, I need to truncate it before writing because it will be updated.

this is how I write element I parsered

url = "https://rocket-league.com/trade/465ec00f-2f5c-48e2-831e-2e294683ad56"
response = requests.get(f"{url}")
soup = BeautifulSoup(response.text, "html.parser")

for e in soup.select('.rlg-trade__itemshas .--hover'):
    items = (' '.join(list(e.stripped_strings)[:-2]))
    lstitem = (f"[H] " f"{items}" + f"\n")
    with open("hs.txt", "a") as h:
        h.write(lstitem)

output:

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

[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl

but when I write it again, output:

[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl
[H] Magma
[H] Pink Light Show
[H] Cristiano
[H] Anodized Pearl

i use h.truncate(0) for truncate before writing, but output like this:

[H] Anodized Pearl

what should I do to interrupt output during loop as if it were first output

>Solution :

You should be opening the file for writing before entering the selection loop. Like this:

import requests
from bs4 import BeautifulSoup

OUTPUT = 'hs.txt'
url = "https://rocket-league.com/trade/465ec00f-2f5c-48e2-831e-2e294683ad56"
(response := requests.get(url)).raise_for_status()
soup = BeautifulSoup(response.text, 'lxml')
with open(OUTPUT, 'w') as h:
    for e in soup.select('.rlg-trade__itemshas .--hover'):
        item = ' '.join(list(e.stripped_strings)[:-2])
        print(f'[H] {item}', file=h)
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