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.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

28 lines
Python 3.9+
def 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

stdout
{'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

  1. Use `os.stat(file_path).st_size` and `open(file_path).readlines()` for a simpler version
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.