Skip to content
Advertisement

Trying to use os.path.exists via variables but getting an error

I have a file called serial.dll. The content of this file is another file’s name:

a-2ED1-7156.dll

I also have 1 file called a-2ED1-7156.dll in the same directory.

When I try to check if the file exists by reading its name from serial.dll:

f = open('serial.dll', 'r')

serials = f.read()

if os.path.exists(serials):
    print("ok")
else:
    print("no")

Always results “no”.

but:

file = 'a-2ED1-7156.dll'

if os.path.exists(file):
    print("ok")
else:    
    print("no")

Always gives the correct result.

How can I check if the file a-2ED1-7156.dll exists by reading it from the serial.dll file?

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

Advertisement

Answer

Your problem is that lines in a file might end with the new-line character. File names usually don’t have that character… For example, right now you’re checking if the file a-2ED1-7156.dlln exists – which is not. You simply need to strip() the lines before checking them as files:

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")
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement