PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 19
Q544 - Modules
Which of the following functions can be used to check if a file exists?
-
A
os.path.isfile() -
B
os.isFile() -
C
os.path.isFile() -
D
os.path.exists()
Reveal correct answer
Correct answer: A
Explanation
Topic: os.path.isfile()
Try it yourself:
- # First execute the following to create the needed folder and file:
- with open('data.txt', 'w') as f:
- f.write('Hello')
- import os
- if not os.path.isdir('folder'):
- os.mkdir('folder')
- # import os
- print(os.path.isfile('data.txt')) # True
- print(os.path.isfile('folder')) # False
- print(os.path.exists('data.txt')) # True
- print(os.path.exists('folder')) # True
- # print(os.isfile('data.txt')) # AttributeError: ...
- # print(os.path.isFile('data.txt')) # AttributeError: ...
Explanation:
The isfile() method is the right choice here.
It checks whether the passed argument is a file.
The exists() method checks if something exists at a given path.
But that could still be a folder.
Python is case sensitive and therefore you have to
write isfile() with a lowercase f
Q544 (Please refer to this number, if you want to write me about this question.)
A. The os.path.isfile() function is the correct choice as it is specifically designed to check if a path is an existing regular file. It returns True if the path exists and is a file, otherwise it returns False.
B. The os.isFile() function is not a valid function in the os module. This function does not exist in Python, so it cannot be used to check if a file exists.
C. The os.path.isFile() function is not a valid function in the os.path module. This function does not exist in Python, so it cannot be used to check if a file exists.
D. The os.path.exists() function is used to check if a path exists, regardless of whether it is a file or directory. While it can be used to check if a file exists, it does not specifically check if the path is a regular file like os.path.isfile() does.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
