Python - 操作系统模块

2023-09-17 22:16:54

可以自动执行许多操作系统任务。Python 中的操作系统模块提供了创建和删除目录(文件夹)、获取其内容、更改和识别当前目录等功能。

首先需要导入 os 模块才能与基础操作系统进行交互。因此,在使用其函数之前,请使用 import os 语句导入它。

获取当前工作目录(Getting Current Working Directory)

getcwd()函数确认返回当前工作目录。

示例: Get Current Working Directory

import os
print(os.getcwd())  #output: 'C:\Python37'

创建目录(Creating a Directory)

我们可以使用 os.mkdir() 函数创建一个新目录,如下所示。

示例: Create a Physical Directory

import os
os.mkdir("C:\MyPythonProject")

将创建一个与函数的字符串参数中的路径对应的新目录。如果打开C:\驱动器,您将看到MyPythonProject文件夹已创建。

默认情况下,如果未在 mkdir() 函数中指定整个路径,它将在当前工作目录或驱动器中创建指定的目录。 以下内容将在C:\Python37目录中创建MyPythonProject

示例: Create a Physical Directory

import os
print(os.getcwd())  #output: 'C:\Python37'
os.mkdir("MyPythonProject")

更改当前工作目录(Changing the Current Working Directory)

在对当前工作目录执行任何操作之前,我们必须首先将当前工作目录更改为新创建的工作目录。这是使用 chdir() 函数完成的。 下面将当前工作目录更改为 C:\MyPythonProject

示例: Change Working Directory

import os
os.chdir("C:\MyPythonProject") # changing current workign directory
print(os.getcwd())  #output: 'C:\MyPythonProject'

您可以将当前工作目录更改为驱动器。下面将C:\驱动器作为当前工作目录。

示例: Change Directory to Drive

os.chdir("C:\")
print(os.getcwd())  #output: 'C:\'

要将当前目录设置为父目录,请使用".."作为chdir()函数中的参数。

示例: Change CWD to Parent

os.chdir("C:\MyPythonProject")
print(os.getcwd())  #output: 'C:\MyPythonProject'
os.chdir("..")
print(os.getcwd()) #output: 'C:\'

删除目录(Removing a Directory)

操作系统模块中的rmdir()功能使用绝对或相对路径删除指定的目录。 请注意,对于要删除的目录,它应为空。

示例: Remove Directory

import os
os.rmdir("C:\MyPythonProject")

但是,您不能删除当前工作目录。若要删除它,必须更改当前工作目录,如下所示。

示例: Remove Directory

import os
print(os.getcwd())  #output: 'C:\MyPythonProject'
os.rmdir("C:\MyPythonProject") #PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
os.chdir("..")
os.rmdir("MyPythonProject")

上面,MyPythonProject不会被删除,因为它是当前目录。 我们使用 os.chdir("..") 将当前工作目录更改为父目录,然后使用 rmdir() 函数将其删除。

列出文件和子目录(List Files and Sub-directories)

listdir()函数返回指定目录中所有文件和目录的列表。

示例: List Directories

import os
print(os.listdir("c:\python37"))

如果我们不指定任何目录,则将返回当前工作目录中的文件和目录列表。

示例: List Directories of CWD

import os
print(os.listdir())  #output: ['.config', '.dotnet', 'python']

了解有关OS modules in Python docs的更多信息。

本文内容总结: