Temporary Directory File Modification Utility

  • Share this:

Code introduction


This function first creates a temporary directory, then copies a file to this directory, then generates a random string as the new filename, modifies the file content, and finally deletes the temporary directory.


Technology Stack : os, string, random, shutil

Code Type : Function

Code Difficulty :


                
                    
import random
import string
import os
import shutil
import datetime

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

def xxx(arg1, arg2, arg3):
    # 创建临时文件夹
    temp_dir = os.path.join(os.getcwd(), generate_random_string())
    os.makedirs(temp_dir, exist_ok=True)
    
    # 复制文件到临时文件夹
    shutil.copy(arg1, temp_dir)
    
    # 生成随机字符串作为文件名
    random_filename = generate_random_string()
    new_file_path = os.path.join(temp_dir, random_filename)
    
    # 修改文件内容
    with open(arg2, 'r') as file:
        content = file.read()
        content = content.replace(arg3, generate_random_string())
    
    with open(new_file_path, 'w') as file:
        file.write(content)
    
    # 删除临时文件夹
    shutil.rmtree(temp_dir)