Reputation: 83
I'm trying to get a random word file from a specified directory, but it returns nothing Here's the some part of the code.
for filename in glob.glob(os.path.join(path, '*docx')):
fl = []
fl.append(filename)
return fl
choice = random.choice(fl)
doc = docx.Document(choice)
print(doc.paragraphs[0].text) # There is a paragraph on the document starting on the first line so problem is not there.
There is nothing wrong with the path. Eveything was working just fine when I was not trying to get only one random file instead of all the files.
Upvotes: 0
Views: 72
Reputation: 4336
In your for
loop logic you are initializing the fl
list every time you are getting the filename
which makes the fl
value to include only last filename(which makes random.choice function give you only same filename), instead rewrite it as,
fl = []
for filename in glob.glob(os.path.join(path, '*docx')):
fl = fl.append(filename)
though the looping is not needed in your case, I suggest you look at what @kra3 answered here.
Upvotes: 1
Reputation: 1578
return fl
is looking kind of odd.
Otherwise it should work.
files = glob.glob(os.path.join(path, '*docx')
choice = random.choice(files) # each time you get a random file out of files.
You don't have to create another list running files through a loop, like you have done.
Upvotes: 2