基于File I/O的随机数文件生成类开发技术问询
Python Class for Generating Random Number Files
Got it, let's tackle this problem step by step. I'll build a Python class that meets all your requirements, plus adds some error handling to make it more reliable for real-world use.
Core Requirements Recap
- Accept two command-line arguments:
- First = filename (overwrites existing files with the same name)
- Second = integer count of random numbers to generate
- Generate random integers between 1 and 1000 (inclusive)
- Write numbers to the file, with exactly 5 numbers per line
Full Implementation Code
import sys import random class RandomNumberFileGenerator: def __init__(self, filename, num_count): self.filename = filename # Validate the number count is a positive integer if not isinstance(num_count, int) or num_count <= 0: raise ValueError("Number of random numbers must be a positive integer") self.num_count = num_count def generate_random_numbers(self): """Generate the specified number of random integers (1-1000)""" return [random.randint(1, 1000) for _ in range(self.num_count)] def write_to_file(self): """Write generated numbers to file, 5 per line""" numbers = self.generate_random_numbers() # Open file in write mode ('w' overwrites existing files) with open(self.filename, 'w') as f: # Iterate over numbers in chunks of 5 for i in range(0, len(numbers), 5): chunk = numbers[i:i+5] # Convert chunk to space-separated string and write line line = ' '.join(map(str, chunk)) f.write(f"{line}\n") if __name__ == "__main__": # Handle command-line arguments if len(sys.argv) != 3: print("Usage: python script.py <filename> <number_of_random_numbers>") sys.exit(1) filename = sys.argv[1] try: num_count = int(sys.argv[2]) except ValueError: print("Error: Second argument must be an integer") sys.exit(1) # Create generator instance and run try: generator = RandomNumberFileGenerator(filename, num_count) generator.write_to_file() print(f"Successfully wrote {num_count} random numbers to {filename}") except Exception as e: print(f"Error: {str(e)}") sys.exit(1)
Key Features Explained
- Error Handling:
- Checks that exactly 2 command-line arguments are provided
- Validates the second argument is a valid integer
- Ensures the number count is positive (no zero or negative numbers)
- Catches general exceptions during file writing or number generation
- File Handling: Uses
with open(...)which automatically closes the file, even if an error occurs - Chunked Writing: Splits the list of random numbers into groups of 5, so each line has exactly 5 values (the last line will have fewer if the total count isn't a multiple of 5)
- Random Number Generation: Uses
random.randint(1, 1000)to get integers in your specified range
How to Use
Run the script from the command line like this:
python random_num_generator.py my_numbers.txt 23
This will create my_numbers.txt with 23 random numbers, 5 per line (the last line will have 3 numbers).
内容的提问来源于stack exchange,提问作者Kyle Lynch
相关产品推荐
相关产品推荐

