python 文件追加写入_Python写入文件–解释了打开,读取,追加和其他文件处理功能

news/2024/7/5 2:17:53

python 文件追加写入

欢迎 (Welcome)

Hi! If you want to learn how to work with files in Python, then this article is for you. Working with files is an important skill that every Python developer should learn, so let's get started.

嗨! 如果您想学习如何在Python中使用文件,那么本文适合您。 处理文件是每个Python开发人员都应该学习的一项重要技能,所以让我们开始吧。

In this article, you will learn:

在本文中,您将学习:

  • How to open a file.

    如何打开文件。
  • How to read a file.

    如何读取文件。
  • How to create a file.

    如何创建文件。
  • How to modify a file.

    如何修改文件。
  • How to close a file.

    如何关闭文件。
  • How to open files for multiple operations.

    如何打开文件进行多种操作。
  • How to work with file object methods.

    如何使用文件对象方法。
  • How to delete files.

    如何删除文件。
  • How to work with context managers and why they are useful.

    如何与上下文管理器一起工作以及它们为何有用。
  • How to handle exceptions that could be raised when you work with files.

    处理文件时如何处理可能引发的异常。
  • and more!

    和更多!

Let's begin! 🔅

让我们开始! 🔅

使用文件:基本语法 (Working with Files: Basic Syntax)

One of the most important functions that you will need to use as you work with files in Python is open(), a built-in function that opens a file and allows your program to use it and work with it.

在Python中处理文件时,需要使用的最重要的功能之一是open() ,它是一个内置函数,可以打开文件并允许您的程序使用它并对其进行处理。

This is the basic syntax:

这是基本语法

💡 Tip: These are the two most commonly used arguments to call this function. There are six additional optional arguments. To learn more about them, please read this article in the documentation.

提示:这是调用此函数的两个最常用的参数。 有六个其他可选参数。 要了解有关它们的更多信息,请阅读文档中的这篇文章 。

第一个参数:文件 (First Parameter: File)

The first parameter of the open() function is file, the absolute or relative path to the file that you are trying to work with.

open()函数的第一个参数是file ,即您要使用的文件的绝对或相对路径。

We usually use a relative path, which indicates where the file is located relative to the location of the script (Python file) that is calling the open() function.

我们通常使用相对路径,该路径指示文件相对于调用open()函数的脚本(Python文件)的位置。

For example, the path in this function call:

例如,此函数调用中的路径:

open("names.txt") # The relative path is "names.txt"

Only contains the name of the file. This can be used when the file that you are trying to open is in the same directory or folder as the Python script, like this:

只包含文件名。 当您要打开的文件与Python脚本位于同一目录或文件夹中时,可以使用此命令,例如:

But if the file is within a nested folder, like this:

但是,如果文件位于嵌套文件夹中,则如下所示:

Then we need to use a specific path to tell the function that the file is within another folder.

然后,我们需要使用特定的路径来告诉函数该文件在另一个文件夹中。

In this example, this would be the path:

在此示例中,这将是路径:

open("data/names.txt")

Notice that we are writing data/ first (the name of the folder followed by a /) and then names.txt (the name of the file with the extension).

请注意,我们首先写入data/ (文件夹的名称,后跟/ ),然后是names.txt (具有扩展名的文件的名称)。

💡 Tip: The three letters .txt that follow the dot in names.txt is the "extension" of the file, or its type. In this case, .txt indicates that it's a text file.

💡 提示: names.txt中的点names.txt的三个字母.txt是文件的“扩展名”或其类型。 在这种情况下, .txt表示它是一个文本文件。

第二个参数:模式 (Second Parameter: Mode)

The second parameter of the open() function is the mode, a string with one character. That single character basically tells Python what you are planning to do with the file in your program.

open()函数的第二个参数是mode ,它是一个带有一个字符的字符串。 该单个字符基本上可以告诉Python您打算如何使用程序中的文件。

Modes available are:

可用的模式有:

  • Read ("r").

    读( "r" )。

  • Append ("a")

    追加( "a" )

  • Write ("w")

    写( "w" )

  • Create ("x")

    创建( "x" )

You can also choose to open the file in:

您还可以选择在以下位置打开文件:

  • Text mode ("t")

    文字模式( "t" )

  • Binary mode ("b")

    二进制模式( "b" )

To use text or binary mode, you would need to add these characters to the main mode. For example: "wb" means writing in binary mode.

要使用文本或二进制模式,您需要将这些字符添加到主模式。 例如: "wb"表示以二进制模式写入。

💡 Tip: The default modes are read ("r") and text ("t"), which means "open for reading text" ("rt"), so you don't need to specify them in open() if you want to use them because they are assigned by default. You can simply write open(<file>).

💡 提示:默认模式为read( "r" )和text( "t" ),这意味着“ open for read text”( "rt" ),因此如果您需要在open()指定它们,想要使用它们,因为它们是默认分配的。 您可以简单地编写open(<file>)

Why Modes?

为什么选择模式?

It really makes sense for Python to grant only certain permissions based what you are planning to do with the file, right? Why should Python allow your program to do more than necessary? This is basically why modes exist.

对于Python,仅根据您计划对该文件执行的操作授予某些权限确实是对的,对吧? 为什么Python应该允许您的程序执行不必要的工作? 这基本上就是模式存在的原因。

Think about it — allowing a program to do more than necessary can problematic. For example, if you only need to read the content of a file, it can be dangerous to allow your program to modify it unexpectedly, which could potentially introduce bugs.

考虑一下-允许程序执行不必要的工作可能会遇到问题。 例如,如果您只需要读取文件的内容,则允许程序意外修改它可能很危险,这可能会引入错误。

如何读取文件 (How to Read a File)

Now that you know more about the arguments that the open() function takes, let's see how you can open a file and store it in a variable to use it in your program.

现在,您对open()函数采用的参数有了更多的了解,让我们看看如何打开文件并将其存储在变量中以在程序中使用它。

This is the basic syntax:

这是基本语法:

We are simply assigning the value returned to a variable. For example:

我们只是将返回的值分配给变量。 例如:

names_file = open("data/names.txt", "r")

I know you might be asking: what type of value is returned by open()?

我知道您可能会问: open()返回什么类型的值?

Well, a file object.

好吧, 一个 文件对象

Let's talk a little bit about them.

让我们谈谈他们。

文件对象 (File Objects)

According to the Python Documentation, a file object is:

根据Python文档 , 文件对象是:

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.
向基础资源公开面向文件的API(使用诸如read()或write()之类的方法)的对象。

This is basically telling us that a file object is an object that lets us work and interact with existing files in our Python program.

这基本上是在告诉我们文件对象是使我们能够在Python程序中工作并与现有文件进行交互的对象。

File objects have attributes, such as:

文件对象具有属性,例如:

  • name: the name of the file.

    name :文件名。

  • closed: True if the file is closed. False otherwise.

    关闭 :如果文件已关闭,则为True 。 否则为False

  • mode: the mode used to open the file.

    mode :用于打开文件的模式。

For example:

例如:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"

Now let's see how you can access the content of a file through a file object.

现在,让我们看看如何通过文件对象访问文件的内容。

读取文件的方法 (Methods to Read a File)

For us to be able to work file objects, we need to have a way to "interact" with them in our program and that is exactly what methods do. Let's see some of them.

为了使我们能够处理文件对象,我们需要一种在程序中与它们“交互”的方法,而这正是方法的作用。 让我们来看一些。

读() (Read())

The first method that you need to learn about is read(), which returns the entire content of the file as a string.

您需要了解的第一种方法是read() 以字符串形式返回文件的全部内容。

Here we have an example:

这里有一个例子:

f = open("data/names.txt")
print(f.read())

The output is:

输出为:

Nora
Gino
Timmy
William

You can use the type() function to confirm that the value returned by f.read() is a string:

您可以使用type()函数来确认f.read()返回的值是一个字符串:

print(type(f.read()))# Output
<class 'str'>

Yes, it's a string!

是的,这是一个字符串!

In this case, the entire file was printed because we did not specify a maximum number of bytes, but we can do this as well.

在这种情况下,将打印整个文件,因为我们没有指定最大字节数,但是我们也可以这样做。

Here we have an example:

这里有一个例子:

f = open("data/names.txt")
print(f.read(3))

The value returned is limited to this number of bytes:

返回的值限于以下字节数:

Nor

📌 Important: You need to close a file after the task has been completed to free the resources associated to the file. To do this, you need to call the close() method, like this:

重要:任务完成后,您需要关闭文件以释放与该文件关联的资源。 为此,您需要调用close()方法,如下所示:

Readline()与Readlines() (Readline() vs. Readlines())

You can read a file line by line with these two methods. They are slightly different, so let's see them in detail.

您可以使用这两种方法逐行读取文件。 它们略有不同,因此让我们详细了解它们。

readline() reads one line of the file until it reaches the end of that line. A trailing newline character (\n) is kept in the string.

readline()读取文件的一行 ,直到到达该行的末尾。 字符串中保留尾随换行符( \n )。

💡 Tip: Optionally, you can pass the size, the maximum number of characters that you want to include in the resulting string.

💡 提示:(可选)您可以传递大小,即要包含在结果字符串中的最大字符数。

For example:

例如:

f = open("data/names.txt")
print(f.readline())
f.close()

The output is:

输出为:

Nora

This is the first line of the file.

这是文件的第一行。

In contrast, readlines() returns a list with all the lines of the file as individual elements (strings). This is the syntax:

相反, readlines()返回一个列表 ,其中文件的所有行均作为单独的元素(字符串)。 这是语法:

For example:

例如:

f = open("data/names.txt")
print(f.readlines())
f.close()

The output is:

输出为:

['Nora\n', 'Gino\n', 'Timmy\n', 'William']

Notice that there is a \n (newline character) at the end of each string, except the last one.

请注意,每个字符串的末尾都有一个\n (换行符),最后一个除外。

💡 Tip: You can get the same list with list(f).

💡 提示:您可以使用list(f)获得相同的列表。

You can work with this list in your program by assigning it to a variable or using it in a loop:

您可以在程序中使用此列表,方法是将其分配给变量或在循环中使用它:

f = open("data/names.txt")for line in f.readlines():# Do something with each linef.close()

We can also iterate over f directly (the file object) in a loop:

我们还可以在循环中直接遍历f (文件对象):

f = open("data/names.txt", "r")for line in f:# Do something with each linef.close()

Those are the main methods used to read file objects. Now let's see how you can create files.

这些是用于读取文件对象的主要方法。 现在让我们看看如何创建文件。

如何建立档案 (How to Create a File)

If you need to create a file "dynamically" using Python, you can do it with the "x" mode.

如果需要使用Python“动态”创建文件,则可以使用"x"模式进行操作。

Let's see how. This is the basic syntax:

让我们看看如何。 这是基本语法:

Here's an example. This is my current working directory:

这是一个例子。 这是我当前的工作目录:

If I run this line of code:

如果我运行以下代码:

f = open("new_file.txt", "x")

A new file with that name is created:

将创建一个具有该名称的新文件:

With this mode, you can create a file and then write to it dynamically using methods that you will learn in just a few moments.

使用这种模式,您可以创建文件,然后使用将在短时间内学习的方法来动态写入文件。

💡 Tip: The file will be initially empty until you modify it.

💡 提示:该文件最初将为空,直到您对其进行修改。

A curious thing is that if you try to run this line again and a file with that name already exists, you will see this error:

奇怪的是,如果您尝试再次运行此行并且该名称的文件已存在,则会看到此错误:

Traceback (most recent call last):File "<path>", line 8, in <module>f = open("new_file.txt", "x")
FileExistsError: [Errno 17] File exists: 'new_file.txt'

According to the Python Documentation, this exception (runtime error) is:

根据Python文档 ,此异常(运行时错误)为:

Raised when trying to create a file or directory which already exists.
在尝试创建已经存在的文件或目录时引发。

Now that you know how to create a file, let's see how you can modify it.

现在您知道如何创建文件,让我们看看如何修改它。

如何修改文件 (How to Modify a File)

To modify (write to) a file, you need to use the write() method. You have two ways to do it (append or write) based on the mode that you choose to open it with. Let's see them in detail.

要修改(写入)文件,您需要使用write()方法。 您有两种选择打开方式的方式(追加或写入)。 让我们详细了解它们。

附加 (Append)

"Appending" means adding something to the end of another thing. The "a" mode allows you to open a file to append some content to it.

“附加”是指在另一事物的末尾添加事物。 "a"模式允许您打开文件以向其中添加一些内容。

For example, if we have this file:

例如,如果我们有此文件:

And we want to add a new line to it, we can open it using the "a" mode (append) and then, call the write() method, passing the content that we want to append as argument.

然后,我们想向其添加新行,我们可以使用"a"模式(附加)将其打开,然后调用write()方法,并传递要添加的内容作为参数。

This is the basic syntax to call the write() method:

这是调用write()的基本语法 方法:

Here's an example:

这是一个例子:

f = open("data/names.txt", "a")
f.write("\nNew Line")
f.close()

💡 Tip: Notice that I'm adding \n before the line to indicate that I want the new line to appear as a separate line, not as a continuation of the existing line.

💡 提示:请注意,我要在行之前添加\n ,以表示我希望新行显示为单独的行,而不是现有行的延续。

This is the file now, after running the script:

运行脚本后,现在是文件:

💡 Tip: The new line might not be displayed in the file until f.close() runs.

提示:f.close()运行之前,新行可能不会显示在文件中。

(Write )

Sometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the write() method if you open the file with the "w" mode.

有时,您可能希望删除文件的内容,然后将其完全替换为新内容。 如果以"w"模式打开文件,则可以使用write()方法执行此操作。

Here we have this text file:

这里有这个文本文件:

If I run this script:

如果我运行此脚本:

f = open("data/names.txt", "w")
f.write("New Content")
f.close()

This is the result:

结果如下:

As you can see, opening a file with the "w" mode and then writing to it replaces the existing content.

如您所见,以"w"模式打开文件,然后对其进行写入将替换现有内容。

💡 Tip: The write() method returns the number of characters written.

💡 提示: write()方法返回写入的字符数。

If you want to write several lines at once, you can use the writelines() method, which takes a list of strings. Each string represents a line to be added to the file.

如果要一次写入多行,可以使用writelines()方法,该方法采用字符串列表。 每个字符串代表要添加到文件的一行。

Here's an example. This is the initial file:

这是一个例子。 这是初始文件:

If we run this script:

如果我们运行此脚本:

f = open("data/names.txt", "a")
f.writelines(["\nline1", "\nline2", "\nline3"])
f.close()

The lines are added to the end of the file:

这些行将添加到文件末尾:

打开文件进行多种操作 (Open File For Multiple Operations )

Now you know how to create, read, and write to a file, but what if you want to do more than one thing in the same program? Let's see what happens if we try to do this with the modes that you have learned so far:

现在您知道了如何创建,读取和写入文件,但是如果您想在同一程序中做多个事情怎么办? 让我们看看如果我们尝试使用到目前为止所学的模式来执行此操作,会发生什么情况:

If you open a file in "r" mode (read), and then try to write to it:

如果您以"r"模式(读取)打开文件,然后尝试写入该文件:

f = open("data/names.txt")
f.write("New Content") # Trying to write
f.close()

You will get this error:

您将收到此错误:

Traceback (most recent call last):File "<path>", line 9, in <module>f.write("New Content")
io.UnsupportedOperation: not writable

Similarly, if you open a file in "w" mode (write), and then try to read it:

同样,如果以"w"模式打开文件(写),然后尝试读取它:

f = open("data/names.txt", "w")
print(f.readlines()) # Trying to read
f.write("New Content")
f.close()

You will see this error:

您将看到此错误:

Traceback (most recent call last):File "<path>", line 14, in <module>print(f.readlines())
io.UnsupportedOperation: not readable

The same will occur with the "a" (append) mode.

"a" (附加)模式也会发生同样的情况。

How can we solve this? To be able to read a file and perform another operation in the same program, you need to add the "+" symbol to the mode, like this:

我们该如何解决呢? 为了能够在同一程序中读取文件并执行其他操作,需要在模式下添加"+"符号,如下所示:

f = open("data/names.txt", "w+") # Read + Write
f = open("data/names.txt", "a+") # Read + Append
f = open("data/names.txt", "r+") # Read + Write

Very useful, right? This is probably what you will use in your programs, but be sure to include only the modes that you need to avoid potential bugs.

非常有用,对吧? 这可能是您将在程序中使用的方式,但是请确保仅包括避免潜在错误所需的模式。

Sometimes files are no longer needed. Let's see how you can delete files using Python.

有时不再需要文件。 让我们看看如何使用Python删除文件。

如何删除文件 (How to Delete Files )

To remove a file using Python, you need to import a module called os which contains functions that interact with your operating system.

要使用Python删除文件,您需要导入一个名为os的模块,其中包含与操作系统交互的功能。

💡 Tip: A module is a Python file with related variables, functions, and classes.

💡 提示: 模块是具有相关变量,函数和类的Python文件。

Particularly, you need the remove() function. This function takes the path to the file as argument and deletes the file automatically.

特别是,您需要remove() 功能。 此函数将文件的路径作为参数,并自动删除文件。

Let's see an example. We want to remove the file called sample_file.txt.

让我们来看一个例子。 我们要删除名为sample_file.txt的文件。

To do it, we write this code:

为此,我们编写以下代码:

import os
os.remove("sample_file.txt")
  • The first line: import os is called an "import statement". This statement is written at the top of your file and it gives you access to the functions defined in the os module.

    第一行: import os称为“ import语句”。 该语句写在文件的顶部,它使您可以访问os模块中定义的功能。

  • The second line: os.remove("sample_file.txt") removes the file specified.

    第二行: os.remove("sample_file.txt")删除指定的文件。

💡 Tip: you can use an absolute or a relative path.

💡 提示:您可以使用绝对路径或相对路径。

Now that you know how to delete files, let's see an interesting tool... Context Managers!

现在,您知道如何删除文件,让我们来看一个有趣的工具:上下文管理器!

会见上下文管理器 (Meet Context Managers)

Context Managers are Python constructs that will make your life much easier. By using them, you don't need to remember to close a file at the end of your program and you have access to the file in the particular part of the program that you choose.

上下文管理器是Python构造,可以使您的生活更加轻松。 通过使用它们,您无需记住在程序结束时关闭文件,并且可以访问所选程序特定部分中的文件。

句法 (Syntax)

This is an example of a context manager used to work with files:

这是用于处理文件的上下文管理器的示例:

💡 Tip: The body of the context manager has to be indented, just like we indent loops, functions, and classes. If the code is not indented, it will not be considered part of the context manager.

提示:上下文管理器的主体必须缩进,就像我们缩进循环,函数和类一样。 如果代码没有缩进,则不会被视为上下文管理器的一部分。

When the body of the context manager has been completed, the file closes automatically.

上下文管理器的主体完成后,文件将自动关闭。

with open("<path>", "<mode>") as <var>:# Working with the file...# The file is closed here!

(Example)

Here's an example:

这是一个例子:

with open("data/names.txt", "r+") as f:print(f.readlines())

This context manager opens the names.txt file for read/write operations and assigns that file object to the variable f. This variable is used in the body of the context manager to refer to the file object.

该上下文管理器将打开names.txt文件以进行读/写操作,并将该文件对象分配给变量f 。 在上下文管理器的主体中使用此变量来引用文件对象。

尝试再次阅读 (Trying to Read it Again)

After the body has been completed, the file is automatically closed, so it can't be read without opening it again. But wait! We have a line that tries to read it again, right here below:

主体完成后,文件将自动关闭,因此如果不重新打开文件就无法读取。 可是等等! 我们在下面的一行中尝试再次读取它:

with open("data/names.txt", "r+") as f:print(f.readlines())print(f.readlines()) # Trying to read the file again, outside of the context manager

Let's see what happens:

让我们看看发生了什么:

Traceback (most recent call last):File "<path>", line 21, in <module>print(f.readlines())
ValueError: I/O operation on closed file.

This error is thrown because we are trying to read a closed file. Awesome, right? The context manager does all the heavy work for us, it is readable, and concise.

引发此错误是因为我们正在尝试读取已关闭的文件。 太好了吧? 上下文管理器为我们完成了所有繁重的工作,它可读且简洁。

处理文件时如何处理异常 (How to Handle Exceptions When Working With Files)

When you're working with files, errors can occur. Sometimes you may not have the necessary permissions to modify or access a file, or a file might not even exist. As a programmer, you need to foresee these circumstances and handle them in your program to avoid sudden crashes that could definitely affect the user experience.

使用文件时,可能会发生错误。 有时您可能没有修改或访问文件所需的权限,或者甚至可能不存在文件。 作为程序员,您需要预见这些情况并在程序中进行处理,以避免突然崩溃,这肯定会影响用户体验。

Let's see some of the most common exceptions (runtime errors) that you might find when you work with files:

让我们看看使用文件时可能会发现的一些最常见的异常(运行时错误):

FileNotFoundError (FileNotFoundError)

According to the Python Documentation, this exception is:

根据Python文档 ,此异常是:

Raised when a file or directory is requested but doesn’t exist.
在请求文件或目录但不存在时引发。

For example, if the file that you're trying to open doesn't exist in your current working directory:

例如,如果您要打开的文件在当前工作目录中不存在:

f = open("names.txt")

You will see this error:

您将看到此错误:

Traceback (most recent call last):File "<path>", line 8, in <module>f = open("names.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'

Let's break this error down this line by line:

让我们逐行细分此错误:

  • File "<path>", line 8, in <module>. This line tells you that the error was raised when the code on the file located in <path> was running. Specifically, when line 8 was executed in <module>.

    File "<path>", line 8, in <module> 。 该行告诉您,当<path>的文件上的代码运行时,引发了错误。 具体来说,在<module>执行line 8

  • f = open("names.txt"). This is the line that caused the error.

    f = open("names.txt") 。 这是导致错误的行。

  • FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' . This line says that a FileNotFoundError exception was raised because the file or directory names.txt doesn't exist.

    FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' 。 这行说,由于文件或目录names.txt不存在,引发了FileNotFoundError异常。

💡 Tip: Python is very descriptive with the error messages, right? This is a huge advantage during the process of debugging.

💡 提示: Python对错误消息的描述非常正确,对吗? 这是调试过程中的巨大优势。

PermissionError (PermissionError)

This is another common exception when working with files. According to the Python Documentation, this exception is:

这是处理文件时的另一个常见例外。 根据Python文档 ,此异常是:

Raised when trying to run an operation without the adequate access rights - for example filesystem permissions.
在尝试在没有足够访问权限(例如文件系统权限)的情况下运行操作时引发。

This exception is raised when you are trying to read or modify a file that don't have permission to access. If you try to do so, you will see this error:

当您尝试读取或修改没有访问权限的文件时,会引发此异常。 如果尝试这样做,将会看到此错误:

Traceback (most recent call last):File "<path>", line 8, in <module>f = open("<file_path>")
PermissionError: [Errno 13] Permission denied: 'data'

IsADirectoryError (IsADirectoryError)

According to the Python Documentation, this exception is:

根据Python文档 ,此异常是:

Raised when a file operation is requested on a directory.
在目录上请求文件操作时引发。

This particular exception is raised when you try to open or work on a directory instead of a file, so be really careful with the path that you pass as argument.

当您尝试打开目录或使用目录而不是文件时,会引发此特殊异常,因此请务必小心作为参数传递的路径。

如何处理异常 (How to Handle Exceptions)

To handle these exceptions, you can use a try/except statement. With this statement, you can "tell" your program what to do in case something unexpected happens.

要处理这些异常,可以使用try / except语句。 使用此语句,您可以“告诉”您的程序万一发生意外情况该怎么做。

This is the basic syntax:

这是基本语法:

try:# Try to run this code
except <type_of_exception>:# If an exception of this type is raised, stop the process and jump to this block

Here you can see an example with FileNotFoundError:

在这里,您可以看到FileNotFoundError的示例:

try:f = open("names.txt")
except FileNotFoundError:print("The file doesn't exist")

This basically says:

这基本上是说:

  • Try to open the file names.txt.

    尝试打开文件names.txt

  • If a FileNotFoundError is thrown, don't crash! Simply print a descriptive statement for the user.

    如果抛出FileNotFoundError ,请不要崩溃! 只需为用户打印描述性声明。

💡 Tip: You can choose how to handle the situation by writing the appropriate code in the except block. Perhaps you could create a new file if it doesn't exist already.

提示:您可以通过在except块中编写适当的代码来选择处理情况的方法。 也许您可以创建一个新文件(如果尚不存在)。

To close the file automatically after the task (regardless of whether an exception was raised or not in the try block) you can add the finally block.

要在任务完成后自动关闭文件(无论try块中是否引发了异常),都可以添加finally块。

try:# Try to run this code
except <exception>:# If this exception is raised, stop the process immediately and jump to this block
finally: # Do this after running the code, even if an exception was raised

This is an example:

这是一个例子:

try:f = open("names.txt")
except FileNotFoundError:print("The file doesn't exist")
finally:f.close()

There are many ways to customize the try/except/finally statement and you can even add an else block to run a block of code only if no exceptions were raised in the try block.

有很多方法可以自定义try / except / finally语句,并且只有在try块中没有引发异常的情况下,您甚至可以添加else块来运行代码块。

💡 Tip: To learn more about exception handling in Python, you may like to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".

💡 提示:要了解有关Python中异常处理的更多信息,您可能需要阅读我的文章: “如何在Python中处理异常:详细的视觉介绍” 。

综上所述 (In Summary)

  • You can create, read, write, and delete files using Python.

    您可以使用Python创建,读取,写入和删除文件。
  • File objects have their own set of methods that you can use to work with them in your program.

    文件对象具有自己的一组方法,可用于在程序中使用它们。
  • Context Managers help you work with files and manage them by closing them automatically when a task has been completed.

    上下文管理器可帮助您处理文件并通过在任务完成后自动将其关闭来管理文件。
  • Exception handling is key in Python. Common exceptions when you are working with files include FileNotFoundError, PermissionError and IsADirectoryError. They can be handled using try/except/else/finally.

    异常处理是Python中的关键。 处理文件时的常见异常包括FileNotFoundErrorPermissionErrorIsADirectoryError 。 可以使用try / except / else / finally处理它们。

I really hope you liked my article and found it helpful. Now you can work with files in your Python projects. Check out my online courses. Follow me on Twitter. 👍

我真的希望您喜欢我的文章并发现它对您有所帮助。 现在,您可以使用Python项目中的文件了。 查看我的在线课程 。 在Twitter上关注我。 👍

翻译自: https://www.freecodecamp.org/news/python-write-to-file-open-read-append-and-other-file-handling-functions-explained/

python 文件追加写入


http://lihuaxi.xjx100.cn/news/237407.html

相关文章

消息队列的面试题7

1、面试题 如果让你写一个消息队列&#xff0c;该如何进行架构设计啊&#xff1f;说一下你的思路 2、面试官心里分析 其实聊到这个问题&#xff0c;一般面试官要考察两块&#xff1a; &#xff08;1&#xff09;你有没有对某一个消息队列做过较为深入的原理的了解&#xff0c;或…

区块链基础:理论和术语

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自链客区块链技术问答社区&#xff0c;未经允许拒绝转载。 一、区块链&#xff1a; 1.百度百科上对区块链的定义是&#xff1a;区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机 技…

vm

为什么80%的码农都做不了架构师&#xff1f;>>> ps ax -O ppid,flags,mwchan | awk $6 ~ /^D/ || $6 "STAT" 转载于:https://my.oschina.net/doz/blog/1630464

堆和栈的区别 之 数据结构和内存

数据结构的栈和堆 首先在数据结构上要知道堆栈&#xff0c;尽管我们这么称呼它&#xff0c;但实际上堆栈是两种数据结构&#xff1a;堆和栈。 堆和栈都是一种数据项按序排列的数据结构。 栈就像装数据的桶或箱子 我们先从大家比较熟悉的栈说起吧&#xff0c;它是一种具有后进先…

gdb -iex_如何使用IEX Cloud,Matplotlib和AWS在Python中创建自动更新数据可视化

gdb -iexPython is an excellent programming language for creating data visualizations.Python是用于创建数据可视化的优秀编程语言。 However, working with a raw programming language like Python (instead of more sophisticated software like, say, Tableau) presen…

tailf

功能说明&#xff1a;tailf命令几乎等同于tail -f&#xff0c;与tail -f不同的是&#xff0c;如果文件不增长&#xff0c;那么它不会去访问磁盘文件&#xff0c;也不会更改文件的访问时间。tailf命令在工作中的主要使命就是跟踪日志文件&#xff0c;首先将默认输出日志文件的最…

面向对象进阶2 组合

2019独角兽企业重金招聘Python工程师标准>>> 一&#xff1a;命名空间 class Person:Country 中国人 # 静态变量print(Person.Country) alex Person() # 创建了一个空的命名空间 alex.name alex # 对象 alex.Country 泰国人 egon Person() egon.name ego…

区块链和可持续性

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自链客区块链技术问答社区&#xff0c;未经允许拒绝转载。 区块链和可持续性 在区块链算法和区块链平台方面&#xff0c;可持续性可以有多种解释。一方面&#xff0c;任何听说过比特币网络能源需求的…