Python 简明教程

Python - Renaming and Deleting Files

Renaming and Deleting Files in Python

在 Python 中,你可以使用 os 模块中的内置函数重命名和删除文件。这些操作在文件系统中管理文件时非常重要。在本教程中,我们将逐步探究如何执行这些操作。

In Python, you can rename and delete files using built-in functions from the os module. These operations are important when managing files within a file system. In this tutorial, we will explore how to perform these actions step-by-step.

Renaming Files in Python

要在 Python 中重命名文件,你可以使用 os.rename() function . 该函数有两个参数:当前文件名和新文件名。

To rename a file in Python, you can use the os.rename() function. This function takes two arguments: the current filename and the new filename.

Syntax

以下是 Python 中 rename() 函数的基本语法:

Following is the basic syntax of the rename() function in Python −

os.rename(current_file_name, new_file_name)

Parameters

该函数接受以下参数:

Following are the parameters accepted by this function −

  1. current_file_name − It is the current name of the file you want to rename.

  2. new_file_name − It is the new name you want to assign to the file.

Example

这里有一个示例,使用 rename() 函数将现有文件“oldfile.txt”重命名为“newfile.txt”:

Following is an example to rename an existing file "oldfile.txt" to "newfile.txt" using the rename() function −

import os

# Current file name
current_name = "oldfile.txt"

# New file name
new_name = "newfile.txt"

# Rename the file
os.rename(current_name, new_name)

print(f"File '{current_name}' renamed to '{new_name}' successfully.")

以下是上面代码的输出: -

Following is the output of the above code −

File 'oldfile.txt' renamed to 'newfile.txt' successfully.

Deleting Files in Python

你可以在 Python 中使用 os.remove() function 删除文件。该函数会删除由文件名指定的某个文件。

You can delete a file in Python using the os.remove() function. This function deletes a file specified by its filename.

Syntax

以下是 Python 中 remove() 函数的基本语法:

Following is the basic syntax of the remove() function in Python −

os.remove(file_name)

Parameters

该函数接受要删除的文件名作为参数。

This function accepts the name of the file as a parameter which needs to be deleted.

Example

这里有一个示例,使用 remove() 函数删除现有文件“file_to_delete.txt”:

Following is an example to delete an existing file "file_to_delete.txt" using the remove() function −

import os

# File to be deleted
file_to_delete = "file_to_delete.txt"

# Delete the file
os.remove(file_to_delete)

print(f"File '{file_to_delete}' deleted successfully.")

执行上面的代码后,我们得到以下输出: -

After executing the above code, we get the following output −

File 'file_to_delete.txt' deleted successfully.