python 读写文件磁盘上的文件,是经过调用操做系统系统的接口来实现的,经过操做系统提供的接口,来读取或者写入文件,Python 读取文件的步骤以下python
# 使用 open ide
一、打开文件操作系统
f1 = open('t1.txt', 'r',encoding='utf-8')
二、读取文件(文件存在的话,不存在的话,会报FileNotFoundError 错误)3d
data = f1.read()
print(data)
hello worldblog
hello world接口
hello worldutf-8
hello worldit
hello worldclass
假设文件不存在的话,好比打开文件 t2.txt coding
三、关闭文件
f1.close()
使用 with open 方法,当文件读写完成后,会自动帮咱们调用 close 方法
with open('t1.txt', 'r') as f1: print(f1.read())
输出:
hello world
hello world
hello world
hello world
hello world