How to check file data in Python
Check if a file exists and is a regular file, then return its name, size, line count, and first line.
Python code
28 linesdef check_file_data(file_path):
from pathlib import Path
path = Path(file_path)
if not path.exists():
return f"File '{file_path}' does not exist."
if not path.is_file():
return f"'{file_path}' is not a regular file."
size = path.stat().st_size
lines = path.read_text(encoding='utf-8', errors='replace').splitlines()
return {
"exists": True,
"name": path.name,
"size_bytes": size,
"line_count": len(lines),
"first_line": lines[0] if lines else "",
}
if __name__ == "__main__":
import tempfile, os
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write("hello\nworld\n")
temp_path = f.name
result = check_file_data(temp_path)
print(result)
os.unlink(temp_path)
Output
{'exists': True, 'name': 'tmpXXXX.txt', 'size_bytes': 12, 'line_count': 2, 'first_line': 'hello'}
How it works
The path.exists() check prevents errors when the file is missing, and path.is_file() ensures it's not a directory. path.stat().st_size gives the byte size. Reading with read_text and splitlines() counts lines after stripping newline characters. The errors='replace' handles non-UTF-8 characters gracefully.
Common mistakes
- Using `os.path.exists` and forgetting to check if it's a file, not a directory
- Reading binary files as text without handling encoding errors
- Assuming the file is non-empty and indexing `lines[0]` without checking length
Variations
- Use `os.stat(file_path).st_size` and `open(file_path).readlines()` for a simpler version
- Return `None` or raise a custom exception instead of returning error strings
Real-world use cases
- Checking if a config file is present and non-empty before parsing it at app startup.
- Validating that an upload is a real file, not a directory, and reporting its size and size.
- Preparing a file summary for logging or monitoring, including line count and first line.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.