Python 简明教程
Python - File Handling
File Handling in Python
Python 中的文件处理涉及与计算机上的文件交互,从中读取数据或向其中写入数据。Python 提供了多个用于创建、打开、读取、写入和关闭文件的内置函数和方法。本教程涵盖了 Python 中文件处理的基础知识,并附有示例。
File handling in Python involves interacting with files on your computer to read data from them or write data to them. Python provides several built-in functions and methods for creating, opening, reading, writing, and closing files. This tutorial covers the basics of file handling in Python with examples.
Opening a File in Python
若要执行任何文件操作,第一步是要打开该文件。Python 的内置 open() 函数用于以各种模式打开文件,例如读取、写入和追加。在 Python 中打开文件的语法为 −
To perform any file operation, the first step is to open the file. Python’s built-in open() function is used to open files in various modes, such as reading, writing, and appending. The syntax for opening a file in Python is −
file = open("filename", "mode")
其中, filename 是要打开的文件的名称,而 mode 打开文件所用的模式(例如,用于读取的“r”,用于写入的“w”,用于追加的“a”)。
Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., 'r' for reading, 'w' for writing, 'a' for appending).
File Opening Modes
以下是文件打开模式:
Following are the file opening modes −
一旦打开了一个文件并且你拥有一个文件对象,你可以获得与该文件相关的各种信息。
Once a file is opened and you have one file object, you can get various information related to that file.
Example 1
在以下示例中,我们正在以不同的模式打开文件 −
In the following example, we are opening a file in different modes −
# Opening a file in read mode
file = open("example.txt", "r")
# Opening a file in write mode
file = open("example.txt", "w")
# Opening a file in append mode
file = open("example.txt", "a")
# Opening a file in binary read mode
file = open("example.txt", "rb")
Example 2
在此处,我们正在以二进制写入模式 (“wb”) 打开一个名为 “foo.txt” 的文件,打印它的名称,它是否已关闭,以及它的打开模式,然后关闭该文件 −
In here, we are opening a file named "foo.txt" in binary write mode ("wb"), printing its name, whether it’s closed, and its opening mode, and then closing the file −
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not: ", fo.closed)
print ("Opening mode: ", fo.mode)
fo.close()
它将生成以下 output −
It will produce the following output −
Name of the file: foo.txt
Closed or not: False
Opening mode: wb
Reading a File in Python
在 Python 中读取文件涉及以允许读取的模式打开该文件,然后使用各种方法从该文件中提取数据。Python 提供了多种从文件中读取数据的方法 −
Reading a file in Python involves opening the file in a mode that allows for reading, and then using various methods to extract the data from the file. Python provides several methods to read data from a file −
-
read() − Reads the entire file.
-
readline() − Reads one line at a time.
-
readlines − Reads all lines into a list.
Example: Using read() method
在以下示例中,我们正在使用 read() 方法将整个文件读取到一个字符串中 −
In the following example, we are using the read() method to read the whole file into a single string −
with open("example.txt", "r") as file:
content = file.read()
print(content)
以下是所获得的输出 −
Following is the output obtained −
Hello!!!
Welcome to TutorialsPoint!!!
Example: Using readline() method
在此处,我们正在使用 readline() 方法每行读取一行,从而使其能够有效地读取行很大的文件 −
In here, we are using the readline() method to read one line at a time, making it memory efficient for reading large files line by line −
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
以上代码的输出如下所示 −
Output of the above code is as shown below −
Hello!!!
Welcome to TutorialsPoint!!!
Example: Using readlines() method
现在,我们正在使用 readlines() 方法读取整个文件并将其拆分为一个列表,其中每个元素都是一行 −
Now, we are using the readlines() method to read the entire file and splits it into a list where each element is a line −
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end='')
我们得到了如下输出 −
We get the output as follows −
Hello!!!
Welcome to TutorialsPoint!!!
Writing to a File in Python
在 Python 中写入文件涉及以允许写入的模式打开该文件,然后使用各种方法向该文件添加内容。
Writing to a file in Python involves opening the file in a mode that allows writing, and then using various methods to add content to the file.
若要向文件写入数据,请使用 write() 或 writelines() 方法。以写入模式(“w”)打开文件时,该文件的现有内容会被删除。
To write data to a file, use the write() or writelines() methods. When opening a file in write mode ('w'), the file’s existing content is erased.
Example: Using the write() method
在本例中,我们使用 write() 方法将传递给它的字符串写入文件。如果文件以“w”模式打开,它将覆盖任何现有内容。如果文件以“a”模式打开,它将把字符串附加在文件末尾。
In this example, we are using the write() method to write the string passed to it to the file. If the file is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will append the string to the end of the file −
with open("foo.txt", "w") as file:
file.write("Hello, World!")
print ("Content added Successfully!!")
上述代码的输出如下:
Output of the above code is as follows −
Content added Successfully!!
Example: Using the writelines() method
此处,我们使用 writelines() 方法获取一个字符串列表并把每个字符串写到文件中。它可用于一次性写多行。
In here, we are using the writelines() method to take a list of strings and writes each string to the file. It is useful for writing multiple lines at once −
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
print ("Content added Successfully!!")
获得的结果如下 −
The result obtained is as follows −
Content added Successfully!!
Closing a File in Python
我们可以使用 close() 方法在 Python 中关闭文件。关闭文件是文件处理中必不可少的一步,以确保文件使用的所有资源都得到正确释放。完成操作后关闭文件很关键,以防止数据丢失并腾出系统资源。
We can close a file in Python using the close() method. Closing a file is an essential step in file handling to ensure that all resources used by the file are properly released. It is important to close files after operations are completed to prevent data loss and free up system resources.
Example
在本例中,我们文件打开为写模式,将数据写入文件,然后使用 close() 方法关闭文件。
In this example, we open the file for writing, write data to the file, and then close the file using the close() method −
file = open("example.txt", "w")
file.write("This is an example.")
file.close()
print ("File closed successfully!!")
下面显示了产生的输出:
The output produced is as shown below −
File closed successfully!!
Using "with" Statement for Automatic File Closing
with 语句是 Python 中用于文件操作的最佳做法,因为它可确保在退出代码块时自动关闭文件,即使发生异常。
The with statement is a best practice in Python for file operations because it ensures that the file is automatically closed when the block of code is exited, even if an exception occurs.
Example
在本例中,文件在 with 块末尾自动关闭,因此不必显式调用 close() 方法。
In this example, the file is automatically closed at the end of the with block, so there is no need to call close() method explicitly −
with open("example.txt", "w") as file:
file.write("This is an example using the with statement.")
print ("File closed successfully!!")
以下是上面代码的输出: -
Following is the output of the above code −
File closed successfully!!
Handling Exceptions When Closing a File
在执行文件操作时,务必处理潜在异常以确保程序能够优雅地处理错误。
When performing file operations, it is important to handle potential exceptions to ensure your program can manage errors gracefully.
在 Python 中,我们使用 try-finally 块处理关闭文件时的异常。“finally”块可确保无论在 try 块中是否发生错误,文件都会关闭。
In Python, we use a try-finally block to handle exceptions when closing a file. The "finally" block ensures that the file is closed regardless of whether an error occurs in the try block −
try:
file = open("example.txt", "w")
file.write("This is an example with exception handling.")
finally:
file.close()
print ("File closed successfully!!")
执行上面的代码后,我们得到以下输出: -
After executing the above code, we get the following output −
File closed successfully!!