Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

1. Obtain all files in the current directory

You can use the os.listdir(path) function, which returns a list of files or folder names that the folder specified by path contains.

The usage method is as follows:

import os

# Open file
path = "D://data/"
dirs = os.listdir( path )

Output all files and folders
for file in dirs:
   print (file)
Copy the code

2. Traversal folders including subfolders

You can use the os.walk(path) function, which traverses all the files in a directory by walking through the directory tree.

It returns a generator of triples (root, dirs, files),

  • rootRefers to the address of the folder that is being traversed
  • dirsIs alist, the content is the name of all directories in the folder (excluding subdirectories)
  • filesIs alist, the content is all the files in that folder (excluding subdirectories)

The usage method is as follows:

import os

path = "D://data/"
for root, dirs, files in os.walk(path):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))
Copy the code

3. Perform other common OS operations

There are also some common OS operations, such as os.path.exists(path) and os.makedirs(path).

  • os.path.exists(path)Used to determinepathIf the path exists, returnstruefalse
  • os.makedirs(path)Used to createpathThe path.

For example, when downloading a file, you want to enable the resumable breakpoint. That is, before downloading a file, you need to check whether the file exists in the local path first.

if not os.path.exists(path):
    #todo: download file
    downloadFile(path)
else:
    pass
Copy the code

Sometimes when you save a file, an error message may be displayed if the path does not exist. Therefore, check whether the path exists first. If not, create a file first.

if not os.path.exists(path):
    # create path
    os.makedirs(path)
    
# todo: save file
saveFiles()
Copy the code