首页 > 解决方案 > 尝试通过变量使用 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

标签: pythonpython-2.7

解决方案


假设每个文件都在单独的行中,您可以使用

lines = f.readlines()
for line in lines:
    if os.path.exists(line):
        print('ok')

或者仅在所有文件都存在时打印,具体取决于您想要什么。


推荐阅读