3

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

是否有一个 Python 模块可以让您创建任意大小的测试文件?我基本上在寻找类似的东西:

test_1mb_file = test_file_module.create_test_file(size=1048576)
4

4 回答 4

13

你真的不需要写 1MB 来创建一个 1MB 的文件:

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

另一方面,你真的需要一个文件吗?许多 API 采用任何“类文件对象”。并不总是很清楚这是否意味着read,readseek, 逐行迭代或其他什么……但无论如何,您应该能够模拟一个 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
于 2012-11-28T21:34:33.380 回答
2

做就是了:

size = 1000
with open("myTestFile.txt", "wb") as f:
    f.write(" " * size)
于 2012-11-28T21:31:38.090 回答
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模块。

我使用 aNamedTemporaryFile以防您需要外部访问它,否则 atempfile.TemporaryFile就足够了。

于 2012-11-28T21:33:02.877 回答
1

来自@abarnert 和@jedwards 的回答:

mb = 1
with tempfile.TemporaryFile() as tf:
    tf.seek(mb * 1024 * 1024 - 1)
    tf.write(b'0')
    tf.seek(0)
于 2016-09-13T18:47:59.320 回答