如何在 Python 中打开并读取文件
要使用 Python 打开并读取文件,您可以使用以下步骤:
-
使用 open() 函数打开文件
语法:
open(filename, mode)
其中:
-
filename
是要打开的文件的路径。 -
mode
指定以何种模式打开文件,例如 \"r\"(只读)或 \"w\"(写入)。
-
-
处理文件对象
open()
函数返回一个文件对象,可用于执行读取、写入和其他操作。 -
使用 read() 方法读取文件内容
语法:
file_object.read()
read()
方法将返回文件中的整个内容作为字符串。 -
关闭文件
一旦您完成对文件的操作,请使用
close()
方法关闭它以释放系统资源。 -
完整代码示例
<code class="<a style=\'color:#f60; text-decoration:underline;\' href=" https: target="_blank">python"># 打开文件 file = open("my_file.txt", "r") # 读取文件内容 content = file.read() # 关闭文件 file.close() # 打印文件内容 print(content)