Read and close a group of files

时间:2019-04-17 02:10:37

标签: python

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?

1 个答案:

答案 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.