为什么我不能从目录中获取随机文件?

Why can't I get a random file from the directory?

我试图从指定的目录中获取一个随机的 word 文件,但是 returns 什么都没有这是代码的一部分。

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.

路径没有问题。当我不尝试只获取一个随机文件而不是所有文件时,一切工作正常。

  1. 我做错了什么?
  2. 有没有更有效的方法?

return fl 看起来有点奇怪。 否则它应该工作。

files = glob.glob(os.path.join(path, '*docx')
choice = random.choice(files) # each time you get a random file out of files.

您不必像之前那样通过循环创建另一个列表 运行 文件。

在您的 for 循环逻辑中,您每次获得 filename 时都会初始化 fl 列表,这使得 fl 值仅包含最后一个文件名(这使得 random.choice 函数只给你相同的文件名),而不是将其重写为

fl = []
for filename in glob.glob(os.path.join(path, '*docx')):
    fl = fl.append(filename)

尽管您的情况不需要循环,但我建议您查看@kra3 的回答