原文:With Open in Python – With Statement Syntax Example,作者:Kolade Chris
Python 编程语言具有用于处理文件的各种函数和语句。 with
语句和 open()
函数是这些语句和函数中的其中两个。
在本文中,你将学习如何使用 with
语句和 open()
函数在 Python 中处理文件。
open() 在 Python 中做了什么
要在 Python 中处理文件,你必须先打开文件。因此,open()
函数正如其名称所暗示的那样——它为你打开一个文件,以便你可以使用该文件。
要使用 open()
函数,首先要为其声明一个变量。 open()
函数最多需要 3 个参数——文件名、模式和编码。然后,你可以在 print
函数中指定要对文件执行的操作。
my_file = open("hello.txt", "r")
print(my_file.read())
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
那不是全部。open()
函数不会关闭文件,因此你还必须使用 close()
方法关闭文件。
因此,使用 open()
函数的正确方法如下所示:
my_file = open("hello.txt", "r")
print(my_file.read())
my_file.close()
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
读取模式是 Python 中默认的文件模式,所以如果不指定模式,上面的代码仍然可以正常工作:
my_file = open("hello.txt")
print(my_file.read())
my_file.close()
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
with 语句在 Python 中如何运行
with
语句与 open()
函数一起打开文件。
因此,你可以像这样重写我们在 open()
函数示例中使用的代码:
with open("hello.txt") as my_file:
print(my_file.read())
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
与你必须使用 close()
方法关闭文件的 open()
不同,with
语句会在你不告诉它的情况下为你关闭文件。
这是因为 with
语句在后台调用了 2 个内置方法——__enter()__
和 __exit()__
。
__exit()__
方法在你指定的操作完成后关闭文件。
使用 write()
方法,你还可以写入文件,如下所示:
with open("hello.txt", "w") as my_file:
my_file.write("Hello world \n")
my_file.write("I hope you're doing well today \n")
my_file.write("This is a text file \n")
my_file.write("Have a nice time \n")
with open("hello.txt") as my_file:
print(my_file.read())
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
# Have a nice time
你还可以遍历文件并逐行打印文本:
with open("hello.txt", "w") as my_file:
my_file.write("Hello world \n")
my_file.write("I hope you're doing well today \n")
my_file.write("This is a text file \n")
my_file.write("Have a nice time \n")
with open("hello.txt") as my_file:
for line in my_file:
print(line)
# 输出:
# Hello world
# I hope you're doing well today
# This is a text file
# Have a nice time
总结
你可能想知道在 with
和 open()
的组合以及仅 open()
函数之间应该使用哪种方式来处理文件。
我建议你使用 with
和 open()
的组合,因为 with
语句会为你关闭文件,并且你可以编写更少的代码。
继续编码:)