Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么可以';我不能从目录中得到一个随机文件吗?_Python_Random_Ms Word_Docx - Fatal编程技术网

Python 为什么可以';我不能从目录中得到一个随机文件吗?

Python 为什么可以';我不能从目录中得到一个随机文件吗?,python,random,ms-word,docx,Python,Random,Ms Word,Docx,我试图从指定的目录中获取一个随机word文件,但它不返回任何内容,这是代码的某些部分 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 paragr

我试图从指定的目录中获取一个随机word文件,但它不返回任何内容,这是代码的某些部分

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.
这条路没有问题。当我不尝试只获取一个随机文件而不是所有文件时,一切都正常

  • 我做错了什么
  • 有没有更有效的方法

  • 返回fl
    看起来有点奇怪。 否则它应该会起作用

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

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

    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
    循环逻辑中,每次获得
    文件名时,您都会初始化
    fl
    列表,这使得
    fl
    值仅包括最后一个文件名(这使得random.choice函数只提供相同的文件名),而将其重写为

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

    虽然在您的案例中不需要循环,但我建议您查看@kra3的回答。

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

    fl = []
    for filename in glob.glob(os.path.join(path, '*docx')):
        fl = fl.append(filename)
    
    虽然在您的案例中不需要循环,但我建议您看看@kra3的回答