首页 > 解决方案 > Selenium 截图后取消链接 txt 文件

问题描述

我在一个文件夹中有一些 txt 文件,我列出了目录和乱码链接。使用 selenium 访问链接后,我截取了屏幕截图。现在我正在尝试删除此链接 txt 文件。

下面的代码我试过

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import os

path = "E:/xampp/htdocs/spool/"
directories = os.listdir(path)
for dir in directories:
    # print(dir)
    files = os.listdir(path+dir)
    for file in files:
        # print(path+dir+'/'+file)
        f = open(path+dir+'/'+file, "r")
        list = f.read()
        data = list.split("||")
        print(data[1])
        driver = webdriver.Chrome(ChromeDriverManager().install())
        driver.get(data[1])
        driver.save_screenshot(data[0]+'.png')
        driver.close()
        os.unlink(f.name)

问题是取消链接时间它给出以下错误

Traceback (most recent call last):
  File "index.py", line 21, in <module>
    os.unlink(f.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'E:/xampp/htdocs/spool/7/2020-09-1112.txt'

我也用过os.close(3),之后报错”

list = f.read()
OSError: [Errno 9] Bad file descriptor

“截图后如何取消链接?

Version python : Python 3.8.4

标签: pythonpython-3.xseleniumselenium-webdriver

解决方案


这种文件处理方法并不完全安全。如果在我们对文件执行某些操作时发生异常,代码将退出而不关闭文件。

在您的情况下,您忘记关闭文件。

f.close()

我建议使用这种方法来避免这种情况

with open("test.txt", mode= 'r', encoding = 'utf-8') as f:
    # perform file operations
    pass
    # we dont need to explicitly close() the method, it is done internally.

推荐阅读