python41 python 文件的读写
文件的读写
打开
<1>打开⽂件
在python,使⽤open函数,可以打开⼀个已经存在的⽂件,或者创建⼀个新 ⽂件
open(⽂件名,访问模式)
示例如下:
f = open('test.txt', 'w')
关闭⽂件
close( ) 示例如下: # 新建一个文件,文件名为:test.txt f = open('test.txt', 'w') # 关闭这个⽂件 f.close() |
⽂件的读写
<1>写数据(write) 使⽤write()可以完成向⽂件写⼊数据 f = open('test.txt', 'w') f.write('hello world, i am here!') f.close() 运⾏现象:
|
注意: 如果⽂件不存在那么创建,如果存在那么就先清空,然后写⼊数据 <2>读数据(read) 使⽤read(num)可以从⽂件中读取数据,num表示要从⽂件中读取的数据的⻓ 度(单位是字节),如果没有传⼊num,那么就表示读取⽂件中所有的数据 f = open('test.txt', 'r') content = f.read(5) print(content) print("-"*30) content = f.read() print(content) f.close() 运⾏现象:
<3>读数据(readlines 就像read没有参数时⼀样,readlines可以按照⾏的⽅式把整个⽂件中的内容 进⾏⼀次性读取,并且返回的是⼀个列表,其中每⼀⾏的数据为⼀个元素 #coding=utf-8 f = open('test.txt', 'r') content = f.readlines() print(type(content)) i=1 for temp in content: print("%d:%s"%(i, temp)) i+=1 f.close() 运⾏现象:
|
<4>读数据(readline) #coding=utf-8 f = open('test.txt', 'r') content = f.readline() print("1:%s"%content) content = f.readline() print("2:%s"%content) f.close()
|
想⼀想
如果⼀个⽂件很⼤,⽐如5G,试想应该怎样把⽂件的数据读取到内存然后进 ⾏处理呢?