Random String Temp File Creation and JSON Conversion

  • Share this:

Code introduction


This function generates a random string as the filename, creates a temporary file, writes the current time, converts the time to JSON format, and finally deletes the temporary file.


Technology Stack : os, sys, datetime, json

Code Type : Code execution

Code Difficulty : Intermediate


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

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

def xxx(arg1, arg2):
    # 创建一个临时文件
    temp_file = os.path.join(sys.path[0], random_string(10) + '.txt')
    with open(temp_file, 'w') as f:
        # 写入当前时间
        f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    # 读取文件内容并转换为JSON格式
    with open(temp_file, 'r') as f:
        content = f.read()
        json_content = json.dumps({'date': content}, ensure_ascii=False)
    # 删除临时文件
    os.remove(temp_file)
    return json_content