0

我试图通过将其每一行添加到一个列表中来编辑一个文本文件,其中一个已被稍微改变,然后将文本文件截断为零并使用 writelines() 添加每一行旧行和编辑一个以正确的顺序返回。完整代码如下。

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")

文本文件的空状态是:

0:[]

1:[]

2:[]

3:[]

4:[]

5:[]

6:[]

7:[]

8:[]

9:[]

10:[]

11:[]

12:[]

13:[]

14:[]

15:[]

16:[]

17:[]

18:[]

19:[]

20:[]

21:[]

22:[]

23:[]

除了最后写入文件之外的所有内容都可以正常工作。该代码不会产生错误消息。问题是每次运行代码时,在第一行之前都会放置一个看似额外的 158 个空格。它们出现在同一行,在零之前,并且总是正好有 158 个。这种一致性让我相信我犯了某种错误。任何见解将不胜感激。

4

1 回答 1

2

从帮助:

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.

之后您需要.seek(0)确保您在正确的位置:

file.truncate(0)
file.seek(0)
file.writelines(new_lines)
于 2020-06-25T07:16:04.097 回答