是否有用于创建特定大小的测试文件的Python模块?

时间:2012-11-28 21:29:39

标签: python file testing

我有一个上传文件的服务器。我需要将各种文件大小的上传/响应时间分析到该服务器,即上传10kb文件,100mb文件和许多其他大小所需的时间。我想避免手动创建所有文件并存储它们。

是否有Python模块可以让您创建任意大小的测试文件?我基本上都在寻找能够起作用的东西:

test_1mb_file = test_file_module.create_test_file(size=1048576)

4 个答案:

答案 0 :(得分:11)

您实际上不需要写1MB来创建1MB文件:

with open('bigfile', 'wb') as bigfile:
    bigfile.seek(1048575)
    bigfile.write('0')

另一方面,你真的需要一个档案吗?许多API采用任何“类文件对象”。这并不总是很清楚这是否意味着readreadseek,按行或其他方式迭代......但无论如何,您应该能够模拟1MB文件而无需创建更多文件数据不是一次readreadline

PS,如果您实际上没有从Python发送文件,只是创建它们以便以后使用,那么有些工具是专门为这类事情设计的:

dd bs=1024 seek=1024 count=0 if=/dev/null of=bigfile # 1MB uninitialized
dd bs=1024 count=1024 if=/dev/zero of=bigfile # 1MB of zeroes
dd bs=1024 count=1024 if=/dev/random of=bigfile # 1MB of random data

答案 1 :(得分:2)

只是做:

size = 1000
with open("myTestFile.txt", "wb") as f:
    f.write(" " * size)

答案 2 :(得分:1)

我可能会使用像

这样的东西
with tempfile.NamedTemporaryFile() as h:
    h.write("0" * 1048576)
    # Do whatever you need to do while the context manager keeps the file open
# Once you "outdent" the file will be closed and deleted.

这使用Python的tempfile模块。

我使用NamedTemporaryFile以防您需要外部访问权限,否则tempfile.TemporaryFile就足够了。

答案 3 :(得分:1)

来自@abarnert和@jedwards答案:

mb = 1
with tempfile.TemporaryFile() as tf:
    tf.seek(mb * 1024 * 1024 - 1)
    tf.write(b'0')
    tf.seek(0)