在python中创建具有随机名称的多个文件并压缩它们

时间:2016-04-17 13:55:00

标签: python python-2.7

我是Python的新手,

我需要在Dest_Dir(我的目标目录)中创建大量具有随机名称的文件,然后将它们压缩到一个文件中。

有谁知道该怎么做? 我设法使用for循环创建这样的文件到特定文件夹,但它不适合我想创建大量文件(让我们说100) 我创建的名字不是随机的。

import os
import sys
import platform
SRC_Dir = os.path.dirname(__file__)
Dest_Dir = os.path.join(SRC_Dir, 'dest')
items = ["one", "two", "three"]
for item in items:
    #(os.path.join(Dest_Dir, filename), 'wb') as temp_file:
    with open(os.path.join(Dest_Dir, item), 'wb') as f:
        f.write("This is my first line of code")
        f.write("\nThis is my second line of code with {} the first item in my list".format(item))
        f.write("\nAnd this is my last line of code")

1 个答案:

答案 0 :(得分:4)

您可以使用内置的tempfile

import os
import tempfile

for _ in range(100):
    file_descriptor, file_path = tempfile.mkstemp(".txt", "prefix-", Dest_Dir)
    file_handle = open(file_path, "wb")
    # do stuff
    os.close(file_descriptor)
    file_handle.close()

由于我对拉链部分做了评论,我想我也会添加

import os
import tempfile
import zipfile

new_files = []
for _ in range(10):
    file_descriptor, file_path = tempfile.mkstemp(".txt", "prefix-", "/tmp")
    file_handle = open(file_path, "wb")
    file_handle.write("HELLO")
    os.close(file_descriptor)
    file_handle.close()
    new_files.append(file_path)

with zipfile.ZipFile("/tmp/zipped.zip", "w") as zipped:
    for file_path in new_files:
        zipped.write(file_path, os.path.basename(file_path))

这里的zipped.write参数假定归档名称只需要文件名(而不是路径)。