File Operations and Analysis Script

  • Share this:

Code introduction


This function creates a directory, writes a string to a file in that directory, then gets the file's last modification time, generates an MD5 hash of the file, uses a regular expression to match a string, checks if a string exists within another string, and writes all the information to a JSON file.


Technology Stack : os, datetime, hashlib, re, string, random, json

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import os
import sys
import json
import datetime
import hashlib
import re

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def xxx(arg1, arg2, arg3):
    # 创建一个目录
    os.makedirs(arg1, exist_ok=True)
    
    # 将字符串写入文件
    with open(os.path.join(arg1, f"{arg2}.txt"), "w") as file:
        file.write(arg3)
    
    # 获取文件的最后修改时间
    modification_time = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(arg1, f"{arg2}.txt")))
    
    # 生成文件的MD5哈希值
    file_hash = hashlib.md5(open(os.path.join(arg1, f"{arg2}.txt"), "rb").read()).hexdigest()
    
    # 使用正则表达式匹配字符串
    pattern = re.compile(arg4)
    match = pattern.search(arg3)
    
    # 检查字符串是否存在于另一个字符串中
    string_exists = arg5 in arg3
    
    # 将信息写入JSON文件
    info = {
        "filename": f"{arg2}.txt",
        "modification_time": modification_time.isoformat(),
        "hash": file_hash,
        "match": match.group() if match else None,
        "string_exists": string_exists
    }
    with open(os.path.join(arg1, "info.json"), "w") as json_file:
        json.dump(info, json_file)