2017-01-13 14 views
0

私はPythonに関しては中間ですが、モジュールになると私は苦労します。私はプロジェクトに取り組んでおり、現在のディレクトリ(ディレクトリ内の任意のもの)内の任意のディレクトリまたはファイルに変数を割り当てることを試みています。そのディレクトリ内の任意のものを選択し、それを変数に割り当てるだけです。Pythonでファイルをランダムに選択する方法

最終的には、作業ディレクトリ内の任意のオブジェクトに変数を割り当てる必要があります。ありがとうございました。

file = (any random file in the directory) 

編集:これはあまりにも

_files = os.listdir('.') 
number = random.randint(0, len(_files) - 1) 
file_ = _files[number] 

あなたが別のオプションは、特にあなたならば、グロブ使用することです

import random 
import os 
# random.choice selects random element 
# os.listdir lists in current directory 
filename="" 
# filter out directories 
while not os.path.isfile(filename): 
    filename=random.choice(os.listdir(directory_path)) 
with open(filename,'r') as file_obj: 
    # do stuff with file 
+1

'random'モジュールを見てください。 –

+0

[ここ](http://effbot.org/pyfaq/how-do-i-generate-random-numbers-in-python.htm)は、いくつかの 'ランダムな'モジュールの特徴を簡単に見ています。 –

+2

'file = random.choice(os.listdir( 'path/to/dir'))' – tdelaney

答えて

4

を助けた皆に感謝の作品すべてのファイルではなく、一部のファイルから選択したい:

import random, glob 
pattern = "*" # (or "*.*") 
filename = random.choice(glob.glob(pattern)) 
1

を使用することができます:)

1
_files = os.listdir('.') 
number = random.randint(0, len(_files) - 1) 
file_ = _files[number] 

ラインラインORDER BY:

  1. これは、0の間の乱数とディレクトリの長さを選択します
  2. リストにディレクトリ内のすべてのファイルを置く - 1
  3. _fileをランダムファイルに割り当てます。
+0

2行目と3行目の代わりにrandom.choiceを使うことができます – Lucas

関連する問題