python - 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
解决方案
这种文件处理方法并不完全安全。如果在我们对文件执行某些操作时发生异常,代码将退出而不关闭文件。
在您的情况下,您忘记关闭文件。
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.
推荐阅读
- node.js - Axios - Cheerio 如何等待所有信息从服务器加载
- swift - 您如何根据用户输入发送通知?迅速
- symfony5 - 如何解决 Symfony 5.1.5 上的 Lexit JWT 401 错误“由于系统问题无法处理身份验证请求”
- javascript - 在服务器 jquery.min.js:2 POST https://company.co.in/Home/tbl 404 上出现错误(未找到)
- r - 变异数据框以检查两个数据框之间的数据是否重复
- javascript - JS:动态添加链接到某个类的所有元素
- typescript - 属性 'subscriptionClient' 是私有的,只能在类 'WebSocketLink'.ts(2341) 中访问
- reactjs - 如何在 ag 网格中添加动作列,其中每行都有编辑/删除按钮?
- php - 如果与前一个元素具有相同的键,则合并数组
- java - 杰克逊排除扩展类