I need to write a piece of code that will open read and close files in a directory. The problem I'm having is that the files aren't necessarily named in a ordered convention. Is there a function or loop that will step through the files in the directory in whatever order or name they are?
答案 0 :(得分:0)
You have a number of options:
glob.glob
os.listdir
os.walk
glob.glob
returns a list of filenames that match a pattern
glob.glob("my_music/*.mp3")
os.listdir
returns a list of filenames in the specified directory:
os.listdir('/usr/local/bin')
os.walk
is a more complicated beast which handles subdirectories - see https://docs.python.org/3/library/os.html#os.walk for detailed examples.
All of these return lists of filenames that you can then sort according to your requirements and then iterate across.