python 2 教程
文件读取的流程为:
打开文件-->读取数据-->关闭文件
文件打开函数为open,签名如下:
open(name, mode=None, buffering=None)
参数:
有以下两种方式读取文件:
1、try...finally
try: f=open("/root/data.txt","r") print(f.read()) finally: if f: f.close()
2、with.. as
with open("/root/data.txt","r") as f: print(f.read())
文件可以按以下几种方式读取:
1、按字符读取
with open("data.txt","r") as f: print(f.read()) print("----------------") with open("data.txt","r") as f: print(f.read(2))输出:
2、读取所有的行到list
print("----------------") with open("data.txt","r") as f: list=f.readlines() print(list)输出:
3、逐行读取
with open("data.txt","r") as f: line=f.readline() print(line)
输出: