Python: directory operation 文件目录操作

Share:
## Objective: - create directory - create temporary directory - delete directory ## Example ```python import os import tempfile # define the access rights access_rights = 0o755 print("===========================") print("Creating a Directory ") # define the name of the directory to be created path = "/tmp/year" print("Create directory: %s" % path) try: os.mkdir(path, access_rights) except OSError as error: print(error) print("Creation of the directory %s failed" % path) else: print("Successfully created the directory %s" % path) print("===========================") print("Creating a Directory with Subdirectories") path = "/tmp/year/month/week/day" print("Create directory (mkdir -p): %s" % path) try: os.makedirs(path, access_rights) except OSError as error: print(error) print("Creation of the directory %s failed" % path) else: print("Successfully created the directory %s" % path) print("===========================") path = "/tmp/year" print("Delete directory: %s" % path) try: if os.path.exists(path): os.rmdir(path) except OSError as error: print(error) print("Deletion of the directory %s failed" % path) else: print("Successfully deleted the directory %s" % path) print("===========================") path = "/tmp/year" print("Simple method: %s" % path) print("Delete directory: %s" % path) if os.path.exists(path): os.system("rm -r /tmp/year") ``` ## Result ```sh python directory.py =========================== Creating a Directory Create directory: /tmp/year Successfully created the directory /tmp/year =========================== Creating a Directory with Subdirectories Create directory (mkdir -p): /tmp/year/month/week/day Successfully created the directory /tmp/year/month/week/day =========================== Delete directory: /tmp/year [Errno 39] Directory not empty: '/tmp/year' Deletion of the directory /tmp/year failed =========================== Simple method: /tmp/year Delete directory: /tmp/year ``` ![yubao_blog_cover](https://raw.githubusercontent.com/yubaoliu/assets/image/yubao_blog_cover.png)

No comments