2016-04-17 7 views
1

ジップそれらを1つのファイルに変換します。私は<code>Dest_Dir</code>でランダムな名前(私の先のディレクトリ)にファイルを大量に作成する必要があり、そしてジップ、私はPythonで初心者だ</p> <p>をPythonでランダムな名前を持つファイルの乗算量を作成し、それらを

これを行う方法を知っている人はいますか? forのようなファイルを特定のフォルダにループして作成することができましたが、大量のファイルを作成したい場合に適していません。 作成した名前はランダムではありません。

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

コードの試しに[mcve]を入力してください。 – idjaw

+2

まず、['random'](https://docs.python.org/2/library/random.html)と[' zipfile'](https://docs.python.org/2/library)を読んでください。/zipfile.html)モジュール。 – Selcuk

+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を追加します考え出したzip一部について行われたので、ここでの議論では、アーカイブされた名前に対してファイル名(パスではなく)のみが必要であると仮定しています。

関連する問題

 関連する問題