Shachar Hamuzim Rajuan Shachar Hamuzim Rajuan - 1 year ago 74
Python Question

Create multiply amount of files with random names in python

I'm newbie in Python,

I need to create a large quantity of files with random names in

(my destination directory), And then Zip them to one file.

Does anyone have an idea how to do that?
I managed to create files like that with a
loop into a specific folder, but it doesn't fit in case I want to create large amount of file (Lets say 100)
And the names I created aren't random.

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

Answer Source

You could make use of the built-in 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download