I have a file called serial.dll
. The content of this file is another file’s name:
JavaScript
x
2
1
a-2ED1-7156.dll
2
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
:
JavaScript
1
9
1
f = open('serial.dll', 'r')
2
3
serials = f.read()
4
5
if os.path.exists(serials):
6
print("ok")
7
else:
8
print("no")
9
Always results “no”.
but:
JavaScript
1
7
1
file = 'a-2ED1-7156.dll'
2
3
if os.path.exists(file):
4
print("ok")
5
else:
6
print("no")
7
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?
JavaScript
1
28
28
1
Update Try:
2
3
f = open('serial.dll', 'r')
4
lines = f.readline()
5
for line in lines:
6
if os.path.exists(line):
7
print('ok')
8
else:
9
print("no")
10
11
results error:
12
no
13
no
14
no
15
no
16
no
17
no
18
no
19
no
20
no
21
no
22
no
23
ok
24
no
25
no
26
no
27
no
28
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:
JavaScript
1
9
1
f = open('serial.dll')
2
3
for line in f:
4
filename = line.strip()
5
if os.path.exists(filename):
6
print(f"{filename} exists")
7
else:
8
print(f"{filename} doesn't exist")
9