Python Code for File Processing and MD5 Hashing

  • Share this:

Code introduction


os, string, random, re, hashlib, shutil, json, datetime


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : Function

Code Difficulty :


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

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def xxx(arg1, arg2, arg3):
    # 创建一个临时目录
    temp_dir = generate_random_string(10)
    os.makedirs(temp_dir, exist_ok=True)
    
    # 读取输入文件
    with open(arg1, 'r') as file:
        content = file.read()
    
    # 使用正则表达式替换所有大写字母为小写
    content = re.sub(r'[A-Z]', lambda x: x.group().lower(), content)
    
    # 生成文件的MD5值
    md5_hash = hashlib.md5(content.encode()).hexdigest()
    
    # 将内容写入临时文件
    with open(os.path.join(temp_dir, 'output.txt'), 'w') as file:
        file.write(content)
    
    # 将文件移动到当前目录
    shutil.move(os.path.join(temp_dir, 'output.txt'), '.')
    
    # 将文件信息写入JSON文件
    file_info = {
        'name': 'output.txt',
        'md5': md5_hash,
        'size': os.path.getsize('output.txt'),
        'timestamp': datetime.datetime.now().isoformat()
    }
    with open('file_info.json', 'w') as file:
        json.dump(file_info, file)
    
    # 清理临时目录
    shutil.rmtree(temp_dir)