Python Selenium拍摄屏幕截图后取消链接txt文件

Python Selenium拍摄屏幕截图后取消链接txt文件,python,python-3.x,selenium,selenium-webdriver,Python,Python 3.x,Selenium,Selenium Webdriver,我有一些txt文件在一个文件夹中,我列出了目录和装饰链接。使用selenium访问链接后,我拍摄了屏幕截图。现在我正在尝试删除这个链接txt文件 下面的代码我已经试过了 from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys import os path = "E:/xa

我有一些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'
" 截图后如何取消链接

Version python : Python 3.8.4

正如你所看到的,另一个进程正在使用txt文件

我想这就是问题所在;你打开了文件,但没有关闭它

我建议你去参观


尝试调用
f.close()
,然后取消链接。

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

f.close()
在您的情况下,您忘记关闭文件

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.