Python gets a list of files (or directory example)

  • 2020-04-02 09:23:13
  • OfStack

The import of OS
OS. OS. Listdir (path)
Then analyze the files and directories one by one
This can be done easily with a clever combination of the DOS command dir
Gets the method for all files in the directory
CMD = "dir/a-d /B"
List_file = OS. Popen (CMD). Readlines ()
The CMD command is interpreted as/a-d selects A list of all non-directory files /B with only Spaces separating all file names
In the readlines method, you get a list of all the files, so you get all the files in the specified directory
Attached is a method to get all directories:
CMD = "dir /AD /B"
List_file = OS. Popen (CMD). Readlines ()

Related articles: