Python:我的脚本不允许我创建大文件

时间:2013-05-23 09:09:44

标签: python python-2.7

我正在制作一个小的python脚本,它将创建各种形状和大小的随机文件,但它不会让我创建大文件。我希望能够创建大小约8GB的文件,我知道这需要很长时间,但我并不担心。

问题是Python 2.7不会处理我为此而生成的大数字,以便创建将填充我的文件的随机文本。

我的代码的目的是创建具有随机名称和扩展名的文件,用随机数量的垃圾文本填充文件并保存文件。它将继续重复此操作,直到我关闭命令行窗口。

import os
import string
import random


ext = ['.zip', '.exe', '.txt', '.pdf', '.msi', '.rar', '.jpg', '.png', '.html', '.iso']

min = raw_input("Enter a minimum file size eg: 112 (meaning 112 bytes): ")
minInt = int(min)

max = raw_input("Enter a maximum file size: ")
maxInt = int(max)

def name_generator(chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for x in range(random.randint(1,10)))

def text_generator(chars=string.printable + string.whitespace):
    return ''.join(random.choice(chars) for x in range(random.randint(minInt,maxInt)))

def main():
    fileName = name_generator()
    extension = random.choice(ext)
    file = fileName + extension

    print 'Creating ==> ' + file
    fileHandle = open ( file, 'w' )
    fileHandle.write ( text_generator() )
    fileHandle.close()
    print file + ' ==> Was born!'

while 1:
    main()

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

根据以下内容使其变得懒惰:

import string
import random
from itertools import islice

chars = string.printable + string.whitespace
# make infinite generator of random chars
random_chars = iter(lambda: random.choice(chars), '')
with open('output_file','w', buffering=102400) as fout:
    fout.writelines(islice(random_chars, 1000000)) # write 'n' many

答案 1 :(得分:2)

问题不在于python无法处理大数字。它可以。

但是,您尝试将整个文件内容一次放入内存中 - 您可能没有足够的RAM用于此,另外也不想这样做。

解决方案是使用生成器并以块的形式写入数据:

def text_generator(chars=string.printable + string.whitespace):
    return (random.choice(chars) for x in range(random.randint(minInt,maxInt))

for char in text_generator():
    fileHandle.write(char)

但这仍然是非常低效的 - 您希望以例如块的形式编写数据。 10kb而不是单个字节。

答案 2 :(得分:0)

关于效果的评论:您可以使用os.urandom()生成随机字节并使用str.translate()将其转换为输入字符范围来改进它:

import os
import string

def generate_text(size, chars=string.printable+string.whitespace):
    # make translation table from 0..255 to chars[0..len(chars)-1]
    all_chars = string.maketrans('', '')
    assert 0 < len(chars) <= len(all_chars)
    result_chars = ''.join(chars[b % len(chars)] for b in range(len(all_chars)))

    # generate `size` random bytes and translate them into given `chars`
    return os.urandom(size).translate(string.maketrans(all_chars, result_chars))

示例:

with open('output.txt', 'wb') as outfile: # use binary mode
    chunksize = 1 << 20  # 1MB
    N = 8 * (1 << 10)    # (N * chunksize) == 8GB
    for _ in xrange(N):
        outfile.write(generate_text(chunksize))

注意:为避免偏离随机分布,k*len(chars)-1返回的大于os.urandom()的字节应丢弃,k*len(chars) <= 256 < (k+1)*len(chars)