File Information Functions Overview

  • Share this:

Code introduction


This function includes multiple sub-functions to get file information such as size, line count, and age.


Technology Stack : os, re, sys, math, time, json

Code Type : File information acquisition function

Code Difficulty : Intermediate


                
                    
import os
import re
import sys
import math
import time
import json

def get_file_size(file_path):
    if not os.path.exists(file_path):
        return 0
    return os.path.getsize(file_path)

def get_file_size_in_kb(file_path):
    file_size_kb = get_file_size(file_path) / 1024
    return round(file_size_kb, 2)

def count_lines_in_file(file_path):
    with open(file_path, 'r') as file:
        return sum(1 for line in file)

def get_file_age_in_days(file_path):
    current_time = time.time()
    file_time = os.path.getmtime(file_path)
    return round((current_time - file_time) / (24 * 3600), 2)

def get_file_age_in_days_json(file_path):
    age_in_days = get_file_age_in_days(file_path)
    return json.dumps({"file_age_in_days": age_in_days})                
              
Tags: