Directory Creation with Content Writing

  • Share this:

Code introduction


This function creates a directory and writes a file with specified content into it. If the directory does not exist, it will create the directory.


Technology Stack : os, string, random

Code Type : File operation

Code Difficulty : Intermediate


                
                    
import os
import sys
import random
import string
import math
import datetime

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

def xxx(arg1, arg2):
    # 创建一个目录
    os.makedirs(arg1, exist_ok=True)
    # 检查目录是否已存在
    if os.path.exists(arg1):
        # 创建一个随机字符串作为文件名
        filename = random_string()
        # 将字符串写入文件
        with open(os.path.join(arg1, filename), 'w') as file:
            file.write(arg2)
        return f"File '{filename}' created with content '{arg2}' in directory '{arg1}'."
    else:
        return f"Directory '{arg1}' does not exist."                
              
Tags: