Python 简明教程
Python - Directories
Directories in Python
在 Python 中,目录通常称为操作系统中的文件夹,它们是文件系统中用于存储文件和其他目录的位置。它们充当以分层方式对文件分组和管理的方法。
In Python, directories, commonly known as folders in operating systems, are locations on the filesystem used to store files and other directories. They serve as a way to group and manage files hierarchically.
Python 提供了多个模块,主要有 os 和 os.path ,以及 shutil,它们允许你在目录上执行各种操作。
Python provides several modules, primarily os and os.path, along with shutil, that allows you to perform various operations on directories.
这些操作包括创建新目录、浏览现有目录、列出目录内容、更改当前工作目录以及删除目录。
These operations include creating new directories, navigating through existing directories, listing directory contents, changing the current working directory, and removing directories.
Checking if a Directory Exists
在对目录执行操作之前,你通常需要检查它是否存在。我们可以使用 Python 中的 os.path.exists() 函数来检查目录是否存在。
Before performing operations on a directory, you often need to check if it exists. We can check if a directory exists or not using the os.path.exists() function in Python.
此函数接受单个参数,该参数是一个表示文件系统中路径的字符串。此参数可能是: -
This function accepts a single argument, which is a string representing a path in the filesystem. This argument can be −
-
Relative path − A path relative to the current working directory.
-
Absolute path − A complete path starting from the root directory.
Example
在此示例中,我们使用 os.path.exists() 函数检查给定的目录路径是否存在: -
In this example, we check whether the given directory path exists using the os.path.exists() function −
import os
directory_path = "D:\\Test\\MyFolder\\"
if os.path.exists(directory_path):
print(f"The directory '{directory_path}' exists.")
else:
print(f"The directory '{directory_path}' does not exist.")
以下是上面代码的输出: -
Following is the output of the above code −
The directory 'D:\\Test\\MyFolder\\' exists.
Creating a Directory
你使用 os.makedirs() 函数在 Python 中创建新目录。此函数在目录不存在的情况下创建中间目录。
You create a new directory in Python using the os.makedirs() function. This function creates intermediate directories if they do not exist.
os.makedirs() 函数接受你想要创建的 “路径” 作为参数。它可以选择接受 “模式” 参数,该参数指定为新创建目录所设置的权限。它是一个以八进制格式表示的整数(例如,0o755)。如果没有指定,则根据系统的 umask 使用默认权限。
The os.makedirs() function accepts a "path" you want to create as an argument. It optionally accepts a "mode" argument that specifies the permissions o set for the newly created directories. It is an integer, represented in octal format (e.g., 0o755). If not specified, the default permissions are used based on your system’s umask.
Example
在以下示例中,我们使用 os.makedirs() 函数创建一个新目录: -
In the following example, we are creating a new directory using the os.makedirs() function −
import os
new_directory = "new_dir.txt"
try:
os.makedirs(new_directory)
print(f"Directory '{new_directory}' created successfully.")
except OSError as e:
print(f"Error: Failed to create directory '{new_directory}'. {e}")
执行上面的代码后,我们得到以下输出: -
After executing the above code, we get the following output −
Directory 'new_dir.txt' created successfully.
The mkdir() Method
你可以使用 os 模块的 mkdir() method 在当前目录中创建目录。你需要向此方法提供一个参数,其中包含要创建的目录的名称。
You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.
以下是 mkdir() 方法在 Python 中的语法 −
Following is the syntax of the mkdir() method in Python −
os.mkdir("newdir")
Get Current Working Directory
若要在 Python 中检索当前工作目录,可以使用 os.getcwd() function 。该函数返回一个字符串,表示执行 Python 脚本的当前工作目录。
To retrieve the current working directory in Python, you can use the os.getcwd() function. This function returns a string representing the current working directory where the Python script is executing.
Syntax
以下是 getcwd() 函数在 Python 中的基本语法 −
Following is the basic syntax of the getcwd() function in Python −
os.getcwd()
Example
以下是使用 getcwd() 函数显示当前工作目录的示例 −
Following is an example to display the current working directory using the getcwd() function −
import os
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")
我们得到了如下输出 −
We get the output as follows −
Current working directory: /home/cg/root/667ba7570a5b7
Listing Files and Directories
可以使用 os.listdir() 函数列出目录的内容。该函数返回指定目录路径内所有文件和目录的列表。
You can list the contents of a directory using the os.listdir() function. This function returns a list of all files and directories within the specified directory path.
Example
在下面的示例中,我们使用 listdir() 函数列出指定目录路径的内容 −
In the example below, we are listing the contents of the specified directory path using the listdir() function −
import os
directory_path = r"D:\MyFolder\Pictures"
try:
contents = os.listdir(directory_path)
print(f"Contents of '{directory_path}':")
for item in contents:
print(item)
except OSError as e:
print(f"Error: Failed to list contents of directory '{directory_path}'. {e}")
以上代码的输出如下所示 −
Output of the above code is as shown below −
Contents of 'D:\MyFolder\Pictures':
Camera Roll
desktop.ini
Saved Pictures
Screenshots
Changing the Current Working Directory
可以使用 chdir() method 更改当前目录。该方法接受一个参数,即要设为当前目录的目录名称。
You can change the current directory using the chdir() method. This method takes an argument, which is the name of the directory that you want to make the current directory.
Syntax
以下是 chdir() 方法在 Python 中的语法 −
Following is the syntax of the chdir() method in Python −
os.chdir("newdir")
Example
以下是使用 chdir() 方法将当前目录更改为 Desktop 的示例 −
Following is an example to change the current directory to Desktop using the chdir() method −
import os
new_directory = r"D:\MyFolder\Pictures"
try:
os.chdir(new_directory)
print(f"Current working directory changed to '{new_directory}'.")
except OSError as e:
print(f"Error: Failed to change working directory to '{new_directory}'. {e}")
我们得到了如下输出 −
We get the output as shown below −
Current working directory changed to 'D:\MyFolder\Pictures'.
Removing a Directory
可以使用 os.rmdir() method 在 Python 中删除空目录。如果目录包含文件或其他目录,可以使用 shutil.rmtree() 方法递归删除。
You can remove an empty directory in Python using the os.rmdir() method. If the directory contains files or other directories, you can use shutil.rmtree() method to delete it recursively.
Syntax
以下是删除 Python 中目录的基本语法 −
Following is the basic syntax to delete a directory in Python −
os.rmdir(directory_path)
# or
shutil.rmtree(directory_path)
Example
在以下示例中,我们使用 os.rmdir() 方法删除空目录 −
In the following example, we remove an empty directory using the os.rmdir() method −
import os
directory_path = r"D:\MyFolder\new_dir"
try:
os.rmdir(directory_path)
print(f"Directory '{directory_path}' successfully removed.")
except OSError as e:
print(f"Error: Failed to remove directory '{directory_path}'. {e}")
它将生成如下输出:
It will produce the following output −
Directory 'D:\MyFolder\new_dir' successfully removed.