Reputation: 1040
I am attempting to edit a text file by adding each of its lines to a list, where one of them has been altered slightly, and then truncating the text file to zero and using writelines()
to add each of the old lines and the edited one back in the correct order. Full code below:
from bs4 import BeautifulSoup as bsoup
from pathlib import Path
import datetime as dt
import requests as r
import time
def view_scrape(game , filename):
home = r.get(f"https://m.twitch.tv/directory/game/{game}")
page = bsoup(home.text , "html.parser")
p = str(page.find_all("p" , class_ = "tw-ellipsis tw-c-text-alt tw-font-size-5"))
start = p.find("<span class=\"tw-strong\">") + 24
end = p.find("</span> Viewers")
viewers = p[start:end]
if len(viewers) < 1:
time.sleep(0.25)
view_scrape(game , filename)
else:
hour = str(dt.datetime.today().hour)
output_file = Path(str(Path(__file__).parents[0]) + f"/{filename}.txt")
new_lines = []
with open(output_file , "r+") as file:
for line in file.readlines():
if line != "\n":
line = line.strip()
splice = line.find(":")
if line[:splice] == hour:
line = line.replace(line , f"{line[:-1]}{viewers} , ]")
new_lines.append(f"{line}\n")
file.truncate(0)
file.writelines(new_lines)
view_scrape("VALORANT" , "hourly_views")
Where the text file's empty state is:
0:[]
1:[]
2:[]
3:[]
4:[]
5:[]
6:[]
7:[]
8:[]
9:[]
10:[]
11:[]
12:[]
13:[]
14:[]
15:[]
16:[]
17:[]
18:[]
19:[]
20:[]
21:[]
22:[]
23:[]
Everything aside from writing to the file at the end is working properly. The code produces no error messages. The problem is that every time the code is run a seemingly extra 158 spaces are placed in advance of the first line. They appear on the same line, before the zero, and there are always exactly 158 of them. This consistency leads me to believe I have made some sort of error.
Upvotes: 0
Views: 351
Reputation: 1240
From the help:
Help on built-in function truncate:
truncate(pos=None, /) method of _io.TextIOWrapper instance
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO
position as reported by tell(). Returns the new size.
You need to .seek(0)
afterwards to make sure that you're in the right place:
file.truncate(0)
file.seek(0)
file.writelines(new_lines)
Upvotes: 2