2012-03-06 80 views
1

[編輯:參見下面的最終代碼]我有下面的代碼,我試圖找出在哪裏插入random.choice代碼,使其選擇一個單一的文件,複製它,並重復(這裏6次)。選擇並複製一個隨機文件幾次

import os 
import shutil 
import random 

dir_input = str(input("Enter Source Directory: ")) 
src_files = (os.listdir(dir_input)) 

for x in range (0,5): 
    print ('This is the %d time' % x) 
    for file_name in src_files: 
     full_file_name = (os.path.join(dir_input, file_name)) 
     if (os.path.isfile(full_file_name)): 
     print ('copying...' + full_file_name) 
      shutil.copy(full_file_name, r'C:\Dir')) 
else: 
    print ('Finished!') 
+0

這功課嗎? – Daenyth 2012-03-06 17:47:33

+0

旁白:範圍(0,5)不給你6次,它只給你5次。範圍不包括上限。 – DSM 2012-03-06 17:49:41

回答

2

謝謝大家對您的H ELP。隨着我學到了一些東西(並從本論壇的人們獲得幫助),代碼發生了顯着變化。這個網站上的人很棒。下面的代碼:

import os 
import shutil 
import random 
import os.path 

src_dir = 'C:\\' 
target_dir = 'C:\\TEST' 
src_files = (os.listdir(src_dir)) 
def valid_path(dir_path, filename): 
    full_path = os.path.join(dir_path, filename) 
    return os.path.isfile(full_path) 
files = [os.path.join(src_dir, f) for f in src_files if valid_path(src_dir, f)] 
choices = random.sample(files, 5) 
for files in choices: 
    shutil.copy(files, target_dir) 
print ('Finished!') 
1

您的代碼複製所有文件從一個目錄'C:\Dir'每個循環。這似乎並不是你想要的。另外,你說了一個單一的文件。您的代碼只會轉儲輸入目錄中所有內容的列表。您可能還想考慮使用raw_input而不是輸入。以下是我建議:

import os 
import shutil 
import random 

# let's seed the random number, it's at least good practice :-) 
random.seed() 
dir_input = raw_input("Enter Source Directory: ") 
# let's get ONLY the files in this directory 
src_files = [ f for f in os.listdir(dir_input) if os.path.isfile(os.path.join(dir_input,f))] 
for x in range (0,5): 
    print ('This is the %d time' % x) 
    # I'll let you copy this where you want, but this will 
    # choose a random file once per loop 
    print random.choice(src_files) 

讓我知道如果我誤解。

+0

謝謝你。不,這不是功課。我希望它是!我是社會學研究生,我自學Python,所以我可以操縱數據庫的250k txt文件。而且,因爲我是如此新,我必須真正弄清楚這究竟是什麼。 – user1252778 2012-03-06 23:46:07

+0

我對你的倡議印象深刻!祝你在學習中最好! – macduff 2012-03-07 00:02:54

1

篩選第一路徑,所以你得到一個僅包含有效選項列表:如果你想n獨特的文件

def valid_path(dir_path, filename): 
    full_path = os.path.join(dir_path, filename) 
    return os.path.isfile(full_path) 

files = [f for f in src_files if valid_path(dir_input, f)] 

然後,你可以使用random.sample():

choices = random.sample(files, n) 

或者,如果你更想允許同一文件的多個實例:

choices = [random.choice(files) for i in range(n)] 
+0

謝謝,這主要是工作。我有一個錯誤,說「沒有這樣的文件或目錄」與一個驅動器號改變。我認爲這是因爲某種原因在本地尋找的。我將在解決問題時發佈解決方案。我很感激幫助。 – user1252778 2012-03-06 23:48:04

+0

@ user1252778:不客氣。如果您需要更多幫助,請發佈您的更新代碼和/或詳細錯誤消息。 – 2012-03-07 17:48:43

0

派息縮進的最後一條語句,否則你會看到消息5倍的複製過程中,而不是之後。

+0

謝謝!我改變了它。 – user1252778 2012-04-11 23:28:04