python

python中的open函数怎么使用

小亿
84
2024-05-11 15:17:52
栏目: 编程语言

在Python中,open()函数用于打开文件,并返回一个文件对象。它接受两个参数:文件路径和打开模式。

# 打开文件以读取内容
file = open("example.txt", "r") 
content = file.read()
print(content)
file.close()

# 打开文件以写入内容
file = open("example.txt", "w") 
file.write("Hello, World!")
file.close()

# 使用with语句来自动关闭文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

在open()函数中,常用的打开模式包括:

使用完文件之后,应该关闭文件以释放资源。可以使用close()方法来关闭文件,或者使用with语句来自动关闭文件。

0
看了该问题的人还看了