python - 尝试通过变量使用 os.path.exists 但出现错误
问题描述
我有一个名为serial.dll
. 该文件的内容是另一个文件的名称:
a-2ED1-7156.dll
我a-2ED1-7156.dll
在同一目录中也有 1 个文件。
当我尝试通过从以下位置读取文件名来检查文件是否存在时serial.dll
:
f = open('serial.dll', 'r')
serials = f.read()
if os.path.exists(serials):
print("ok")
else:
print("no")
总是结果“不”。
但:
file = 'a-2ED1-7156.dll'
if os.path.exists(file):
print("ok")
else:
print("no")
总是给出正确的结果。
如何a-2ED1-7156.dll
通过从文件中读取文件来检查文件是否存在serial.dll
?
Update Try:
f = open('serial.dll', 'r')
lines = f.readline()
for line in lines:
if os.path.exists(line):
print('ok')
else:
print("no")
results error:
no
no
no
no
no
no
no
no
no
no
no
ok
no
no
no
no
解决方案
假设每个文件都在单独的行中,您可以使用
lines = f.readlines()
for line in lines:
if os.path.exists(line):
print('ok')
或者仅在所有文件都存在时打印,具体取决于您想要什么。
推荐阅读
- java - 如何设置 Maven 在 Spring Boot 中构建特定文件夹?
- python - 在 tabWidget 内的 pyqt5 中使用 matplotlib 绘制另一个图形之前不清除图形
- python - 寻找两部分字母的轮廓
- ios - CVOpenGLESTextureCache & CVMetalTextureCache 正确使用
- java - 无法在 Java 中使用 Aspose PDF 从 PDF 文件中读取内容
- git - 将存储库文件夹链接到另一个非存储库文件夹
- ddev - 我做了一个“ddev start”,看到“web 服务不健康”和“web 服务健康检查超时”
- docker - Lando - 错误:未找到 appserver_1 的容器
- java - PrintStackTrace 导致我的程序崩溃。为什么?
- javascript - 在Javascript中按时间对日期列表进行排序