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