Home > front end >  Python Issue writing txt file
Python Issue writing txt file

Time:09-06

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:

[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

CodePudding user response:

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)
  • Related