尝试通过变量使用 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


墨色风雨
浏览 46回答 2
2回答

智慧大石

假设每个文件都在单独的行中,您可以使用lines = f.readlines()for line in lines:    if os.path.exists(line):        print('ok')或者仅在所有文件都存在时才打印,具体取决于您想要的内容。

沧海一幻觉

您的问题是文件中的行可能以换行符结尾。文件名通常没有该字符...例如,现在您正在检查文件是否a-2ED1-7156.dll\n存在 - 但实际上不存在。您只需要在将strip()它们作为文件检查之前就可以:f = open('serial.dll')for line in f:    filename = line.strip()    if os.path.exists(filename):        print(f"{filename} exists")    else:        print(f"{filename} doesn't exist")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python