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

在python中创建大量具有随机名称的文件并压缩它们,python,python-2.7,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 = [

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

您可以使用内置的
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
参数假定存档名称只需要文件名(而不是路径)。

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

压缩。此处的write
参数假定存档名称只需要文件名(而不是路径)。

请提供您的代码尝试的详细信息。您应该首先阅读和模块。他的意思可能是fit not feet,推断…..这更容易理解吗?您在
项中已经有了iterable=[“一”、“二”、“三”]
,现在只需使用
random
模块中的工具将其替换为所需的随机文件名类型。请提供您的代码尝试的详细信息。您应该首先阅读和模块。他可能是指fit not feet,推断…..这更容易理解吗?您在
items=[”中已经有了iterable“一”、“二”、“三”]
,现在只需使用
random
模块中的工具将其替换为所需的随机文件名类型即可。