我试图在批处理或python中创建20个.tmp文件。我一直在寻找一切,却找不到解决办法。我希望.tmp文件存储在C:\Users\%USERNAME%\AppData\Local\Temp中,这是代码。
Python:
import tempfile
# This makes a .tmp file but only 0kb i want like 37kb
for i in range(20):
new_file, filename = tempfile.mkstemp('.tmp')
print(filename)这将生成一个.tmp文件,但我希望增加它所需的大小/存储空间。
我没有分批的方法,所以请帮助我,所有的支持都很感激
发布于 2022-07-26 10:32:11
下面的函数可以用来将(n)字节的随机数据写入指定的文件中。
使用os.urandom函数生成随机字节数,并将其写入指定给fpath函数参数的文件路径。
注意:因为这是二进制数据,所以它不是人类可读的,但考虑到它只是随机数据填充文件,这应该无关紧要。
def write_temp_file(fpath: str, size: int):
"""Create a temp file filled with (n) random bytes.
Args:
fpath (str): Full path to the file.
size (int): Number of bytes to write into the file.
"""
with open(fpath, 'wb') as f:
f.write(os.urandom(size))使用:
>>> write_temp_file('/tmp/tempfile.tmp', 37000)输出:
我使用的是Linux,所以文件显示有点不同,但是您可以看到一个文件已经写成了37‘m大小。
$ la /tmp/temp*
-rw-rw-r-- 1 user group 37K Jul 26 11:29 tempfile.tmp创建许多.tmp文件:
如果您想要生成许多.tmp文件,可以将函数调用包装在一个循环中,例如:
for i in range(1, 21):
n = str(i).zfill(2)
write_temp_file(f'/tmp/tempfile{n}.tmp', 37000)输出:
$ la /tmp/temp*
-rw-rw-r-- 1 user group 37000 Jul 26 11:42 /tmp/tempfile01.tmp
-rw-rw-r-- 1 user group 37000 Jul 26 11:42 /tmp/tempfile02.tmp
...
-rw-rw-r-- 1 user group 37000 Jul 26 11:42 /tmp/tempfile19.tmp
-rw-rw-r-- 1 user group 37000 Jul 26 11:42 /tmp/tempfile20.tmphttps://stackoverflow.com/questions/73121199
复制相似问题