【问题标题】:python builtin file.writelines() is confusing mepython builtin file.writelines() 让我感到困惑
【发布时间】:2020-10-15 13:54:01
【问题描述】:

我正在尝试通过将文本文件的每一行添加到列表中来编辑文本文件,其中一个已被稍微更改,然后将文本文件截断为零并使用 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 个。这种一致性让我相信我犯了某种错误。任何见解将不胜感激。

【问题讨论】:

  • 您正在读取和写入同一个文件!您必须写入不同的文件。为此,在当前的 open.. 之外添加另一个 open(new_file, "w") ... 并写入它。
  • 这是有原因的吗?我认为将第一个文件设置为完全空,然后再写入就可以了。
  • @FiftyBill 没有详细查看代码,但我看不出您将文件用作读/写的具体问题。
  • @FiftyBill 啊,也许truncate() 没有定位文件指针。您可能需要从头开始。
  • 无论如何,感谢您的帮助!覆盖文件完美!

标签: python python-3.x write


【解决方案1】:

来自帮助:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多