exists and is_file
- Python course
- Intermediate
- Lesson 78/116
- 5 min
Learn checks with exists, is_file, is_dir.
Checking with exists and is_file
You check whether a path exists with p.exists(); it returns True or False. To tell files from folders you use p.is_file() and p.is_dir().
These checks keep you safe before file operations; for example you can verify a file exists before opening it. For a folder, is_file() returns false; for a folder is_dir() returns true. If the file doesn't exist, both return false.
Create a file with write_text
You can create a file from a Path object in one line: p.write_text("hello", encoding="utf-8"). This creates the file if missing, or replaces its content if it exists. It's shorter than writing with open(...).
For reading you use p.read_text(encoding="utf-8"); it returns all content as a single string. These methods are practical for small and medium files; for large files you still prefer streaming reads with open.
Practice Create a file and check with exists
Start with from pathlib import Path. Create a path object with p = Path("test.txt"). Write to the file with p.write_text("hello", encoding="utf-8"). Print its existence with print(p.exists()) and whether it's a file with print(p.is_file()).
Starter code
# Import the Path class
# Create the p path object and write with write_text
# Check with exists and is_file, printSample solution
# Import the Path class
from pathlib import Path
# Create the p path object and write with write_text
p = Path("test.txt")
p.write_text("hello", encoding="utf-8")
# Check with exists and is_file, print
print(p.exists())
print(p.is_file())Expected output
True True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the checking methods
| Term | Meaning |
|---|---|
exists |
Existence check |
is_file |
File check |
is_dir |
Folder check |
write_text |
Write text to a file |
2 What does is_file() return for a missing file?
- True
- False Correct answer
- None
- Raises an error
Explanation: For a missing path is_file() returns false; no error is raised.
3 Complete the exists call
p = Path("test.txt")
print(p.____())
p = Path("test.txt")
print(p.exists())
Explanation: exists() checks existence.