如何在Python中打开和关闭文件
可能会出现需要使用Python与外部文件交互的情况。 Python提供了用于创建、写入和读取文件的内置函数。
在本文中,我们将讨论如何使用Python打开和关闭外部文件。
在Python中打开文件:
在Python中可以处理两种类型的文件,普通文本文件和二进制文件(用二进制语言编写,0s 和 1s)。打开文件是指准备好文件以供读取或写入。这可以使用open()函数来完成。此函数返回一个文件对象并接受两个参数,一个接受文件名,另一个接受模式(访问模式)。
注意:该文件应与Python脚本位于同一目录下,否则应写入文件的完整地址。
Syntax: File_object = open(“File_Name”, “Access_Mode”)
Parameters:
- File_Name: It is the name of the file that needs to be opened.
- Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python:
Operation | Syntax | Description |
---|---|---|
Read Only | r | Open text file for reading only. |
Read and Write | r+ | Open the file for reading and writing. |
Write Only | w | Open the file for writing. |
Write and Read | w+ | Open the file for reading and writing. Unlike “r+” is doesn’t raise an I/O error if file doesn’t exist. |
Append Only | a | Open the file for writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified. |
Append and Read | a+ | Open the file for reading and writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified. |
示例 1:
在此示例中,我们将以只读方式打开文件。初始文件如下所示:
代码:
Python3
# open the file using open() function
file = open("sample.txt")
# Reading from file
print(file.read())
Python3
# open the file using open() function
file = open("sample.txt", 'a')
# Add content in the file
file.write(" This text has been newly appended on the sample file")
Python3
# open the file using open() function
file = open("sample.txt", 'w')
# Overwrite the file
file.write(" All content has been overwritten !")
Python3
# open the file using open() function
file = open("sample.txt")
# Reading from file
print(file.read())
# closing the file
file.close()
Python3
# open the file using open() function
file = open("sample.txt")
# Reading from file
print(file.read())
# closing the file
file.close()
# Attempt to write in the file
file.write(" Attempt to write on a closed file !")
在这里,我们打开了文件并打印了它的内容。
输出:
Hello Geek!
This is a sample text file for the example.
示例 2:
在此示例中,我们将向现有文件附加新内容。所以初始文件如下所示:
代码:
Python3
# open the file using open() function
file = open("sample.txt", 'a')
# Add content in the file
file.write(" This text has been newly appended on the sample file")
现在,如果您打开文件,您将看到以下结果,
输出:
示例 3:
在此示例中,我们将使用以下代码覆盖示例文件的内容:
代码:
Python3
# open the file using open() function
file = open("sample.txt", 'w')
# Overwrite the file
file.write(" All content has been overwritten !")
上面的代码导致以下结果,
输出:
在Python中关闭文件:
如果您注意到,我们没有关闭我们在上述示例中操作的任何文件。尽管如果文件的引用对象被分配给另一个文件, Python会自动关闭文件,但标准做法是关闭打开的文件,因为关闭的文件可以降低被无端修改或读取的风险。
Python有一个close()方法来关闭一个文件。可以多次调用 close() 方法,如果对已关闭的文件执行任何操作,则会引发 ValueError。
下面的代码显示了使用 close() 方法关闭打开的文件的简单方法。
示例 1:
Python3
# open the file using open() function
file = open("sample.txt")
# Reading from file
print(file.read())
# closing the file
file.close()
现在,如果我们尝试对关闭的文件执行任何操作,如下所示,它会引发 ValueError:
Python3
# open the file using open() function
file = open("sample.txt")
# Reading from file
print(file.read())
# closing the file
file.close()
# Attempt to write in the file
file.write(" Attempt to write on a closed file !")
输出:
ValueError: I/O operation on closed file.