Python reads files randomly
The following code
import os
import random
rootdir = "d:\\face\\train"
file_names = []
for parent, dirnames, filenames in os.walk(rootdir): #3 Parameters: returns respectively 1. The parent directory 2. All folder names (not including paths) 3. All file names
file_names = filenames
# for filename in filenames: # Output file information
# print("parent is" + parent)
# print("filename is:" + filename)
# print("the full name of the file is:" + os.path.join(parent, filename))
x = random.randint(0, len(file_names)-1)
print(file_names[x])
Pay attention to
1. This code passed the test on Python 3.5
2.rootdir parameter means the directory of the folder you want to traverse. Please modify it according to your actual needs
Thank you for reading, I hope to help you, thank you for your support of this site!