Python實現(xiàn)生成指定大小文件的示例詳解
如題,做測試的懂的都懂,不多解釋
相比其他大佬,本腳本基于gpt編寫后整理,生成的文件更真實,能夠打開預(yù)覽,看過其他人的生成腳本,只是一個符合大小,但是是空白或不能打開的文件。
話不多說,看示例,記得在創(chuàng)建一個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." # 要重復(fù)的文本
text_size_bytes = len(text.encode('utf-8')) # 每個重復(fù)的文本的大?。ㄒ宰止?jié)為單位)
repetitions = file_size_bytes // text_size_bytes # 需要重復(fù)的次數(shù)
remainder = file_size_bytes % text_size_bytes # 剩余的字節(jié)數(shù)
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
# 計算所需的像素數(shù)量
num_pixels = (memory_size * 1024 * 1024) // 3 # 每個像素占用 3 個字節(jié)(RGB模式)
# 根據(jù)像素數(shù)量計算圖片的長和寬
img_width = int(np.sqrt(num_pixels))
img_height = int(num_pixels / img_width)
# 創(chuàng)建一個隨機顏色的數(shù)組
pixels = np.random.randint(0, 256, (img_height, img_width, 3), dtype=np.uint8)
# 根據(jù)數(shù)組創(chuàng)建圖片對象
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 文件的大小通常由數(shù)據(jù)量和內(nèi)容決定,而不是像 Excel 那樣可以直接控制行高和列寬。CSV 文件的大小可能會受到編碼和分隔符的影響
generate_csv(target_memory_mb=10) # Change target memory size as needed方法補充
除了上面的方法,小編還為大家整理了其他生成指定大小文件夾的方法,需要的可參考下
方法一:使用os模塊
我們可以使用os模塊中的truncate()函數(shù)來設(shè)置文件的大小。示例如下:
import os
#創(chuàng)建一個1GB大小的文件
file_name = "test.txt"
with open(file_name, 'w') as f:
f.write(" " * 1024) # 寫入1KB的空數(shù)據(jù)
f.seek(1024 * 1024 * 1024) # 定位到文件末尾
f.write("EOF")
f.truncate() # 設(shè)置文件大小上述代碼中,我們首先打開一個文件test.txt,并寫入1KB的空數(shù)據(jù)。然后,我們移動文件指針到1GB位置,并在文件末尾加上EOF表示文件結(jié)束。最后,我們使用truncate()函數(shù)來設(shè)置文件大小為1GB。
方法二:使用fallocate命令
除了使用Python內(nèi)置的函數(shù),我們還可以使用系統(tǒng)的命令來創(chuàng)建特定大小的文件。Linux系統(tǒng)中有一個fallocate命令,可以直接分配文件所在的磁盤空間。
我們可以使用subprocess模塊來執(zhí)行系統(tǒng)命令。示例如下:
import subprocess # 創(chuàng)建一個1GB大小的文件 file_name = "test.txt" subprocess.run(['fallocate', '-l', '1G', file_name])
上述代碼中,我們使用subprocess.run()函數(shù)來執(zhí)行系統(tǒng)命令fallocate -l 1G test.txt,即在當(dāng)前目錄下創(chuàng)建一個1GB大小的文件test.txt。
方法三:使用dd命令
除了fallocate命令外,我們還可以使用Linux系統(tǒng)中的dd命令來創(chuàng)建特定大小的文件。
示例如下:
import subprocess #創(chuàng)建一個1GB大小的文件 file_name = "test.txt" subprocess.run(['dd', 'if=/dev/zero', 'of=' + file_name, 'bs=1M', 'count=1024'])
上述代碼中,我們使用dd命令來創(chuàng)建一個1GB大小的文件test.txt。if=/dev/zero表示輸入設(shè)備為數(shù)據(jù)全為0的設(shè)備,of=后跟上要創(chuàng)建的文件名,bs=1M表示每次寫入1MB的數(shù)據(jù),count=1024表示寫入1024次,即共計1GB。
到此這篇關(guān)于Python實現(xiàn)生成指定大小文件的示例詳解的文章就介紹到這了,更多相關(guān)Python生成文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python 2.6.6升級到Python2.7.15的詳細(xì)步驟
這篇文章主要介紹了Python 2.6.6升級到Python2.7.15的詳細(xì)步驟,本文分步驟給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
matplotlib之Font family [‘sans-serif‘] not&nbs
本文主要介紹了matplotlib之Font family [‘sans-serif‘] not found的問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Python數(shù)據(jù)分析入門之?dāng)?shù)據(jù)讀取與存儲
今天繼續(xù)帶大家學(xué)習(xí)python數(shù)據(jù)分析,下文中有非常詳細(xì)的代碼示例,清楚地解釋了python數(shù)據(jù)讀取與存儲的相關(guān)知識,需要的朋友可以參考下2021-05-05

