2017-03-14 6 views
0
import os 
import random 

path = os.listdir(r"file path here") 
list = [os.listdir(r"life path here")] 


print(len(path)) 

for i in range(len(path)): 
    full_path = (r"file path here" + path[i]) 
    print(full_path) 
print_random_items = random.randint(0, len(path[i])) 
print(print_random_items) 

randintから値を印刷:私は値が15である場合15番目のファイル名を印刷したいだから、こんにちは、私は(print_random_items)私は印刷に値の復帰に関連付けられているファイルの名前を印刷することができます方法を知っている</p> <p>EXを希望

最初にこの形式を間違えて質問してください。

+0

ヒント:ファイル名には固有の順序はありません。例えば、 https://www.tutorialsp.com/.com/python/os_listdir.htm – kay

答えて

0

乱数を気にしないでください。例えば

random.choice(paths) 

::ちょうどrandom.choiceを使用

>>> import random 
>>> paths = os.listdir('./exampledir') 
>>> paths 
['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt', 'f.txt'] 
>>> random.choice(paths) 
'e.txt' 
>>> random.choice(paths) 
'c.txt' 

注:あなたがPythonのスタイルの反復に慣れていない私はあなたのコードで表示さ

この

for i in range(len(path)): 
    full_path = (r"file path here" + path[i]) 
    print(full_path) 

が良く

for partial_path in path: 
    full_path = r"file path here" + partial_path 
    print(full_path) 

そうではなく、あなただけの直接pathを反復処理することができますインデックスを取得するためにrange(len(path))を使用して書かれています。

+0

ええと、私はちょうどまだ学習をコーディングし始めました。 –

関連する問題