Python study notes-create an empty folder in the current path

aims

Create the mydata folder in the current path, and empty it if the mydata folder already exists.


Functions used

os.getcwd()

Return to the current working directory.

os.path.exists()

If path exists, return True; if path does not exist, return False.

os.walk ()

The os.walk() method is a simple and easy-to-use file and directory traversal device that can help us process files and directories efficiently.

The syntax format is as follows:

os.walk(top[, topdown=True[, οnerrοr=None[, followlinks=False]]])

top - is the address of the directory you want to traverse, and what is returned is a triple (root, dirs, files).

  • Root refers to the address of the folder itself that is currently being traversed
  • dirs is a list, the content is the name of all the directories in the folder (not including subdirectories)
  • files also list, the contents of the folder are all the files (not including subdirectories)

topdown - Optional, True, the top directory will be traversed first, otherwise the sub-directories of top will be traversed first (the default is on). If the topdown parameter is True, walk will traverse the top folder and every subdirectory in the top folder.

onerror - Optional, requires a callable object, it will be called when walk needs an exception.

followlinks - optional, if True, it will traverse the directory actually pointed to by the shortcut under the directory (soft connection symbolic link under linux) (closed by default), if it is False, the subdirectories of top will be traversed first.

os.remove ()

Delete the file in the specified path . If the specified path is a directory, OSError will be thrown.

os.rmdir ()

Delete the directory of the specified path . Only if the folder is empty, otherwise, OSError will be thrown.

os.path.join()

Combine the directory and file name into a path.

os.mkdir()

Create directories in digital permission mode. The default mode is 0777 (octal).


Code

# -*- coding: utf-8 -*-
import os

#创建mydata文件夹
#如果mydata文件夹已存在,清空文件夹(先清空后删除再创建)
pathd=os.getcwd()+'\\mydata'
if os.path.exists(pathd): #判断mydata文件夹是否存在
    for root, dirs, files in os.walk(pathd, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name)) #删除文件
        for name in dirs:
            os.rmdir(os.path.join(root, name)) #删除文件夹
    os.rmdir(pathd) #删除mydata文件夹
os.mkdir(pathd) #创建mydata文件夹

 

Guess you like

Origin blog.csdn.net/qq_14997473/article/details/90408675