Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否有用于创建特定大小的测试文件的Python模块?_Python_File_Testing - Fatal编程技术网

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

是否有用于创建特定大小的测试文件的Python模块?,python,file,testing,Python,File,Testing,我有一个上传了文件的服务器。我需要分析不同文件大小到该服务器的上传/响应时间,即上传10kb文件、100mb文件和许多其他大小的文件所需的时间。我希望避免手动创建所有文件并存储它们 是否有Python模块允许您创建任意大小的测试文件?我基本上是在寻找这样的东西: test_1mb_file = test_file_module.create_test_file(size=1048576) 只要做: size = 1000 with open("myTestFile.txt", "wb") as

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

是否有Python模块允许您创建任意大小的测试文件?我基本上是在寻找这样的东西:

test_1mb_file = test_file_module.create_test_file(size=1048576)
只要做:

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

我可能会用像这样的东西

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的模块


我使用了一个名为TemporaryFile的
文件,以防您需要外部访问它,否则一个
tempfile.TemporaryFile
就足够了。

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

with open('bigfile', 'wb') as bigfile:
    bigfile.seek(1048575)
    bigfile.write('0')
另一方面,你真的需要一个文件吗?许多API采用任何“类似文件的对象”。这是否意味着
read
read
seek
,逐行迭代,或者其他什么,并不总是很清楚……但不管是什么,您应该能够模拟1MB文件,而不必一次创建比单个
read
readline
更多的数据

另外,如果您实际上不是从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

来自@abarnert和@jedwards的答案:

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

请注意,如果您想要特别大的文件,可能需要将其拆分为许多较小的写入,以防止内存不足。寻找此类模块是否比找到一个3到5行程序来执行所需功能所需的时间更长?不要误解我的意思,重用通常是一个好主意,而不是重新发明,但是当手头的任务非常琐碎时……在python 3.6中,您需要使用bigfile.write(b'0'),因为它需要一个字节对象来写入字节流