在python中用随机名称创建成倍数量的文件并压缩它们

2024-04-26 10:28:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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")

Tags: 文件ofpathimportforisosmy
1条回答
网友
1楼 · 发布于 2024-04-26 10:28:43

您可以使用内置的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()

既然有人对zip部分发表了评论,我想我也会加上这一点

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参数假定存档名称只需要文件名(而不是路径)。你知道吗

相关问题 更多 >