Python实现生成指定大小文件的示例详解
作者:测试超有范
如题,做测试的懂的都懂,不多解释
相比其他大佬,本脚本基于gpt编写后整理,生成的文件更真实,能够打开预览,看过其他人的生成脚本,只是一个符合大小,但是是空白或不能打开的文件。
话不多说,看示例,记得在创建一个data目录。
代码示例:
import os
import time
import csv
from PIL import Image
import random
import numpy as np
import imageio
import cv2
# pip install opencv-python
# pip install Pillow
def generate_txt(file_size):
file_size_bytes = 1024 * 1024 * file_size
file_path = './data/txt' + time.strftime('%Y%m%d') + '_' + str(file_size) + 'M.txt'
text = "Women only affect the speed at which I type Pythong code." # 要重复的文本
text_size_bytes = len(text.encode('utf-8')) # 每个重复的文本的大小(以字节为单位)
repetitions = file_size_bytes // text_size_bytes # 需要重复的次数
remainder = file_size_bytes % text_size_bytes # 剩余的字节数
with open(file_path, 'w') as file:
for _ in range(repetitions):
file.write(text)
if remainder > 0:
file.write(text[:remainder])
print("生成完成")
def generate_video(target_filesize_mb, frame_width=1920, frame_height=1080, frame_rate=30):
temp_filename = './data/image' + time.strftime('%Y%m%d') + '_' + str(target_filesize_mb) + 'M.mp4'
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter(temp_filename, fourcc, frame_rate, (frame_width, frame_height))
while True:
frame = np.random.randint(0, 256, (frame_height, frame_width, 3), dtype=np.uint8)
out.write(frame)
current_filesize = (len(open(temp_filename, "rb").read())) / (1024 * 1024) # in MB
if current_filesize >= target_filesize_mb:
break
out.release()
def generate_image(memory_size, filename):
"""
:param memory_size: 生成图片的大小,单位是m
:param filename: 生成图片的文件格式
:return:
"""
filename = './data/image'+ time.strftime('%Y%m%d') +'_'+ str(memory_size) + 'M' '.'+filename
# 计算所需的像素数量
num_pixels = (memory_size * 1024 * 1024) // 3 # 每个像素占用 3 个字节(RGB模式)
# 根据像素数量计算图片的长和宽
img_width = int(np.sqrt(num_pixels))
img_height = int(num_pixels / img_width)
# 创建一个随机颜色的数组
pixels = np.random.randint(0, 256, (img_height, img_width, 3), dtype=np.uint8)
# 根据数组创建图片对象
image = Image.fromarray(pixels, 'RGB')
image.save(filename)
def generate_csv(target_memory_mb):
file_name = './data/csv_utf8 ' + time.strftime('%Y%m%d') +"_"+ str(target_memory_mb) + 'M.csv'
row_data = "Data" * 100 # Adjust length to control memory usage per row
with open(file_name, 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file)
while os.path.getsize(file_name) / (1024 * 1024) < target_memory_mb:
writer.writerow([row_data])
if __name__ == '__main__':
# 生成一个大小为2MB的TXT文件
generate_txt(2)
# 生成15M视频
generate_video(target_filesize_mb=15)
# 生成一个10M 的png的图片
generate_image(10, "png")
# 以utf-8的格式,生成一个10M的csv文件 CSV 文件的大小通常由数据量和内容决定,而不是像 Excel 那样可以直接控制行高和列宽。CSV 文件的大小可能会受到编码和分隔符的影响
generate_csv(target_memory_mb=10) # Change target memory size as needed方法补充
除了上面的方法,小编还为大家整理了其他生成指定大小文件夹的方法,需要的可参考下
方法一:使用os模块
我们可以使用os模块中的truncate()函数来设置文件的大小。示例如下:
import os
#创建一个1GB大小的文件
file_name = "test.txt"
with open(file_name, 'w') as f:
f.write(" " * 1024) # 写入1KB的空数据
f.seek(1024 * 1024 * 1024) # 定位到文件末尾
f.write("EOF")
f.truncate() # 设置文件大小上述代码中,我们首先打开一个文件test.txt,并写入1KB的空数据。然后,我们移动文件指针到1GB位置,并在文件末尾加上EOF表示文件结束。最后,我们使用truncate()函数来设置文件大小为1GB。
方法二:使用fallocate命令
除了使用Python内置的函数,我们还可以使用系统的命令来创建特定大小的文件。Linux系统中有一个fallocate命令,可以直接分配文件所在的磁盘空间。
我们可以使用subprocess模块来执行系统命令。示例如下:
import subprocess # 创建一个1GB大小的文件 file_name = "test.txt" subprocess.run(['fallocate', '-l', '1G', file_name])
上述代码中,我们使用subprocess.run()函数来执行系统命令fallocate -l 1G test.txt,即在当前目录下创建一个1GB大小的文件test.txt。
方法三:使用dd命令
除了fallocate命令外,我们还可以使用Linux系统中的dd命令来创建特定大小的文件。
示例如下:
import subprocess #创建一个1GB大小的文件 file_name = "test.txt" subprocess.run(['dd', 'if=/dev/zero', 'of=' + file_name, 'bs=1M', 'count=1024'])
上述代码中,我们使用dd命令来创建一个1GB大小的文件test.txt。if=/dev/zero表示输入设备为数据全为0的设备,of=后跟上要创建的文件名,bs=1M表示每次写入1MB的数据,count=1024表示写入1024次,即共计1GB。
到此这篇关于Python实现生成指定大小文件的示例详解的文章就介绍到这了,更多相关Python生成文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
