简体   繁体   English

如何从文件夹中打印多个随机文件名?

[英]How can I print several random file names from a folder?

I have a folder with 310 txt files and I want to print 248 random file names (without repetition) from these txt files.我有一个包含 310 个 txt 文件的文件夹,我想从这些 txt 文件中打印 248 个随机文件名(不重复)。 I have tried out the following code, but it only outputs 1 random file name instead of 248 file names at once.我尝试了以下代码,但它一次只输出 1 个随机文件名,而不是 248 个文件名。

import os
import random
path = "C:\Python\Python37-32\lindenberg_txt"
files = os.listdir(path)
index = random.randrange(0, len(files))
print(files[index])

Python version used: 3.7使用的 Python 版本:3.7

import os

import random

path = r"C:\Python\Python37-32\lindenberg_txt"

files = os.listdir(path)

random.shuffle(files)

print(files[0:248])

random.choice returns a random element in a list you can use it with a loop to make a new list random.choice 返回列表中的随机元素,您可以将其与循环一起使用以创建新列表

new_list = []
index = random.randint(0,len(files)-1)
for i in range(index)
     new_list += [random.choice(files)]

use this code:使用此代码:

import os
import random
path = "C:\Python\Python37-32\lindenberg_txt"
files = os.listdir(path)
print([files[random.randint(0, len(files) - 1)] for i in range(0, 248)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM