[英]Printing a value from a randint
import os
import random
path = os.listdir(r"file path here")
list = [os.listdir(r"life path here")]
print(len(path))
for i in range(len(path)):
full_path = (r"file path here" + path[i])
print(full_path)
print_random_items = random.randint(0, len(path[i]))
print(print_random_items)
So Hi I would like to know how I can print the name of the file associated with the value return to print(print_random_items) 因此,嗨,我想知道如何打印与该值关联的文件的名称并返回到print(print_random_items)
ex: If the value is 15 I would like to print the 15th files name 例如:如果值为15,我想打印第15个文件名
First time asking a question here sorry if the format is wrong. 第一次在这里提出问题,对不起格式是否错误。
Don't bother with the random numbers. 不要打扰随机数。 Just use random.choice
: 只需使用random.choice
:
random.choice(paths)
For example: 例如:
>>> import random
>>> paths = os.listdir('./exampledir')
>>> paths
['a.txt', 'b.txt', 'c.txt', 'd.txt', 'e.txt', 'f.txt']
>>> random.choice(paths)
'e.txt'
>>> random.choice(paths)
'c.txt'
Note: I see in your code that you are not familiar with python style iteration. 注意:我在您的代码中看到您不熟悉python样式迭代。
This 这个
for i in range(len(path)):
full_path = (r"file path here" + path[i])
print(full_path)
is better written as 最好写成
for partial_path in path:
full_path = r"file path here" + partial_path
print(full_path)
So rather than using range(len(path))
to get an index you can just iterate over path
directly. 因此,与其使用range(len(path))
来获取索引,不如直接在path
进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.