File Creation with Data Writing and Delay

  • Share this:

Code introduction


This function accepts three arguments: the target directory path (arg1), the data to be written (arg2), and the waiting time (arg3). The function first checks if the target directory exists, and if not, it creates it. Then it writes the data to a file named data.txt in the target directory. After that, the function waits for the specified time and returns a JSON-formatted message.


Technology Stack : os, sys, time, json, random, string

Code Type : File manipulation and time processing

Code Difficulty : Intermediate


                
                    
import os
import sys
import time
import json
import re
import random
import string

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

def xxx(arg1, arg2, arg3):
    if not os.path.exists(arg1):
        os.makedirs(arg1)
    with open(os.path.join(arg1, 'data.txt'), 'w') as file:
        file.write(arg2)
    time.sleep(arg3)
    return json.dumps({"message": "File created and data written successfully"})