Skip to content

FILE METADATA AND ATTRIBUTES - Checking file information

Python
#!/usr/bin/env python3
"""
FILE METADATA AND ATTRIBUTES - Checking file information
Demonstrates reading file properties and metadata
"""

import os
import tempfile
import time
from datetime import datetime

print("=" * 60)
print("FILE METADATA - Inspecting File Attributes")
print("=" * 60)

temp_dir = tempfile.gettempdir()

# Create sample files
sample_file = os.path.join(temp_dir, "sample.txt")
with open(sample_file, 'w') as f:
    f.write("This is a sample file.\n")
    f.write("It has multiple lines.\n")
    f.write("Used for metadata demonstration.\n")

# Example 1: File size
print("\n1. File Size")
print("-" * 40)
size = os.path.getsize(sample_file)
print(f"  Size in bytes: {size}")
print(f"  Size in KB: {size / 1024:.2f}")
print(f"  Size in MB: {size / (1024 * 1024):.6f}")

# Example 2: File existence and type
print("\n2. File Existence and Type")
print("-" * 40)
print(f"  File exists: {os.path.exists(sample_file)}")
print(f"  Is file: {os.path.isfile(sample_file)}")
print(f"  Is directory: {os.path.isdir(sample_file)}")
print(f"  Is symbolic link: {os.path.islink(sample_file)}")

# Example 3: File timestamps
print("\n3. File Timestamps")
print("-" * 40)
stat_info = os.stat(sample_file)

created_time = stat_info.st_ctime
modified_time = stat_info.st_mtime
accessed_time = stat_info.st_atime

print(f"  Created: {datetime.fromtimestamp(created_time)}")
print(f"  Modified: {datetime.fromtimestamp(modified_time)}")
print(f"  Accessed: {datetime.fromtimestamp(accessed_time)}")

# Example 4: File age
print("\n4. File Age")
print("-" * 40)
current_time = time.time()
age_seconds = current_time - modified_time
age_minutes = age_seconds / 60
age_hours = age_minutes / 60

print(f"  Age: {age_seconds:.2f} seconds")
print(f"  Age: {age_minutes:.2f} minutes")
print(f"  Age: {age_hours:.6f} hours")

# Example 5: File permissions
print("\n5. File Permissions")
print("-" * 40)
mode = stat_info.st_mode
print(f"  Mode (octal): {oct(mode)}")
print(f"  Readable: {os.access(sample_file, os.R_OK)}")
print(f"  Writable: {os.access(sample_file, os.W_OK)}")
print(f"  Executable: {os.access(sample_file, os.X_OK)}")

# Example 6: File path components
print("\n6. File Path Components")
print("-" * 40)
print(f"  Full path: {sample_file}")
print(f"  Directory: {os.path.dirname(sample_file)}")
print(f"  Filename: {os.path.basename(sample_file)}")
print(f"  Name without ext: {os.path.splitext(sample_file)[0]}")
print(f"  Extension: {os.path.splitext(sample_file)[1]}")

# Example 7: Multiple files statistics
print("\n7. Multiple Files Statistics")
print("-" * 40)

# Create more test files
test_files = []
for i in range(3):
    tf = os.path.join(temp_dir, f"test_{i}.txt")
    with open(tf, 'w') as f:
        f.write("x" * (100 * (i + 1)))
    test_files.append(tf)

total_size = 0
for tf in test_files:
    size = os.path.getsize(tf)
    total_size += size
    print(f"  {os.path.basename(tf)}: {size} bytes")

print(f"  Total size: {total_size} bytes")

# Example 8: File content preview with metadata
print("\n8. File Preview with Metadata")
print("-" * 40)

def file_info(filepath):
    """Get comprehensive file information"""
    stat = os.stat(filepath)

    with open(filepath, 'r') as f:
        lines = f.readlines()
        first_line = lines[0].strip() if lines else ""

    info = {
        'name': os.path.basename(filepath),
        'size': stat.st_size,
        'lines': len(lines),
        'modified': datetime.fromtimestamp(stat.st_mtime),
        'preview': first_line[:50]
    }
    return info

info = file_info(sample_file)
print(f"  File: {info['name']}")
print(f"  Size: {info['size']} bytes")
print(f"  Lines: {info['lines']}")
print(f"  Modified: {info['modified']}")
print(f"  Preview: {info['preview']}...")

# Example 9: Check if file is empty
print("\n9. Check if File is Empty")
print("-" * 40)
empty_file = os.path.join(temp_dir, "empty.txt")
with open(empty_file, 'w') as f:
    pass  # Create empty file

print(f"  sample.txt empty: {os.path.getsize(sample_file) == 0}")
print(f"  empty.txt empty: {os.path.getsize(empty_file) == 0}")

# Example 10: File comparison by metadata
print("\n10. Compare Files by Modification Time")
print("-" * 40)
file1 = sample_file
file2 = test_files[0]

mtime1 = os.path.getmtime(file1)
mtime2 = os.path.getmtime(file2)

if mtime1 > mtime2:
    print(f"  {os.path.basename(file1)} is newer")
elif mtime2 > mtime1:
    print(f"  {os.path.basename(file2)} is newer")
else:
    print(f"  Both files have same modification time")

# Example 11: Generate file report
print("\n11. Generate File Report")
print("-" * 40)
report_file = os.path.join(temp_dir, "file_report.txt")

files_to_report = [sample_file] + test_files

with open(report_file, 'w') as report:
    report.write("FILE METADATA REPORT\n")
    report.write("=" * 60 + "\n\n")

    for filepath in files_to_report:
        stat = os.stat(filepath)
        report.write(f"File: {os.path.basename(filepath)}\n")
        report.write(f"  Path: {filepath}\n")
        report.write(f"  Size: {stat.st_size} bytes\n")
        report.write(f"  Modified: {datetime.fromtimestamp(stat.st_mtime)}\n")
        report.write(f"  Readable: {os.access(filepath, os.R_OK)}\n")
        report.write(f"  Writable: {os.access(filepath, os.W_OK)}\n")
        report.write("\n")

print(f"Generated report: {report_file}")
with open(report_file, 'r') as f:
    print(f.read())

# Cleanup
for f in [sample_file, empty_file, report_file] + test_files:
    if os.path.exists(f):
        os.remove(f)

print("\n" + "=" * 60)
print("Key Points:")
print("  - os.path.getsize() for file size")
print("  - os.stat() for detailed metadata")
print("  - os.path functions for path manipulation")
print("  - os.access() for permission checking")
print("  - Timestamps for modification tracking")
print("=" * 60)