Temporary File Creation and Content Retrieval

  • Share this:

Code introduction


This function accepts two string arguments, writes them into a temporary file, then reads the file content and returns it. It also records the creation time of the file and deletes the file after reading.


Technology Stack : String, random string generation, file operations, time handling, system paths

Code Type : Function

Code Difficulty : Intermediate


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

def random_string(length=10):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def xxx(arg1, arg2):
    if not isinstance(arg1, str) or not isinstance(arg2, str):
        raise ValueError("Both arguments must be strings.")
    if not arg1 and not arg2:
        raise ValueError("At least one argument must not be empty.")
    
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    file_name = random_string(10) + ".txt"
    with open(file_name, 'w') as file:
        file.write(arg1)
        file.write("\n")
        file.write(arg2)
        file.write("\n")
        file.write("Timestamp: " + current_time)
    
    content = file.read()
    file_path = os.path.join(sys.path[0], file_name)
    
    # Remove file after reading
    os.remove(file_path)
    
    return content