You can download this code by clicking the button below.
This code is now available for download.
This function accepts two arguments: a directory path and a length value. The function first checks if the path exists, then randomly selects a file from the files in that path, reads its content, and returns the content of the first arg2 characters.
Technology Stack : os, string, random, json, sys, time
Code Type : File manipulation and random selection
Code Difficulty : Intermediate
import os
import json
import random
import string
import sys
import time
def generate_random_string(length=10):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def xxx(arg1, arg2):
if not os.path.isdir(arg1):
raise FileNotFoundError(f"The provided path {arg1} does not exist.")
files = [f for f in os.listdir(arg1) if os.path.isfile(os.path.join(arg1, f))]
selected_file = random.choice(files)
file_path = os.path.join(arg1, selected_file)
try:
with open(file_path, 'r') as file:
content = file.read()
except IOError as e:
raise IOError(f"Failed to read file {file_path}: {e}")
if len(content) > arg2:
return content[:arg2]
else:
return content