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