Python 创建文本文件:随机行数、字符数和大写字母
Python 创建随机文本文件
该程序使用 Python 创建一个文本文件,文件内容包含随机行数、字符数和大写字母。
功能:
- 创建指定路径的目录(如果目录不存在)
- 生成指定行数和字符数的文本文件
- 文件内容为随机生成的大写字母
代码:
import os
import random
# 创建目录
if not os.path.exists('d:/Python'):
os.mkdir('d:/Python')
# 随机行数和字符数
line_num = random.randint(10, 20)
char_num = random.randint(10, 30)
# 随机生成大写字母
letters = [chr(i) for i in range(65, 91)]
# 创建文件并写入内容
with open('d:/Python/1.txt', 'w') as f:
for i in range(line_num):
line = ''.join(random.choices(letters, k=char_num))
f.write(line + '\n')
运行程序后,会在 d:/Python 目录下创建一个名为 1.txt 的文件,文件中包含了随机生成的大写字母。
原文地址: https://www.cveoy.top/t/topic/nYh1 著作权归作者所有。请勿转载和采集!