简体   繁体   中英

Read and close a group of files

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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