Why does the same way of opening and writing a file gives me error the second time? ValueError: I/O operation on closed file

Why does the same way of opening and writing a file gives me error the second time? ValueError: I/O operation on closed file

我正在尝试在“api obs.txt”上写一个打开的 YouTube 视频的标题,在“link obs.txt”上写它的 URL .标题已写入,但显示“ValueError:I/O 对已关闭文件的操作。”在写 URL.

while True:
    atual = driver.current_url
    with open('link obs.txt', 'r') as file:
        linksalvo = file.readline()

  #if current is different than the saved url
if atual != linksalvo: 
    #write the new title on the file for the api to read
    with open('api obs.txt', 'w') as f:
        sys.stdout = f
        html = urlopen(atual)
        html = BeautifulSoup(html.read().decode('utf-8'), 'html.parser')
        print(html.title.get_text())
        #write the URL of the current video to the file for comparison later
    with open('link obs.txt', 'w') as f:
        print(driver.current_url) #"ValueError: I/O operation on closed file." Happens on this line

        
    sys.stdout = original_stdout

在您执行 sys.stdout = f 之后,对 f 的任何操作也会对 sys.stdout 执行。离开 with 块会关闭 f,因此它也会关闭 sys.stdout

然后当您稍后执行 print(driver.current_url) 时,它会尝试将其写入 sys.stdout,但它已关闭,因此您会收到错误消息。打开第二个文件后需要再次使用sys.stdout = f

我建议您首先不要重新定义 sys.stdout。您可以使用 print()file 参数来写入特定的文件对象。

if atual != linksalvo: 
    #write the new title on the file for the api to read
    with open('api obs.txt', 'w') as f:
        html = urlopen(atual)
        html = BeautifulSoup(html.read().decode('utf-8'), 'html.parser')
        print(html.title.get_text(), file=f)
        #write the URL of the current video to the file for comparison later
    with open('link obs.txt', 'w') as f:
        print(driver.current_url, file=f) #"ValueError: I/O operation on closed file." Happens on this line