file读操作
首先我们在本地项目里面创建一个1.txt,你的python脚本要和这个txt文件保持在同一个目录下
我们写入
11
23
aa
bb
import codecs
f=codecs.open('1.txt')
text = f.read()
result = text.replace('1','AA')
print (result)
f.close()
AAAA
23
aa
bb
file写操作
#wirte()必须传入一个字符串
#wirte()必须传入一个序列传入格式为[‘aa\n’,’bb\n’]
#mode有几个参数需要注意
#r 读
#w 写
#b 二进制
#a 追加
f1=codecs.open('2.txt','w')
f1.write('hello word!\n')
f1.write('hello dada!\n')
f1.close()
f2=codecs.open('2.txt','ab')
f2.write('hello {0}!\n'.format('liao'))
f2.write('hello %s!\n' %'chao')
f2.close()
对应这个脚本的目录下会生成一个2.txt文件,并且内容为:
hello word!
hello dada!
hello liao!
hello chao!
file的常用方法
f3 =codecs.open('2.txt')
#readline和readlines都是按指针来读取的,读到哪里指针就跟到哪里,所以文件只能读取一遍
#readlines()将一行组成一个字符串,然后放到一个列表里
print (f3.readlines())
[‘hello word!\r\n’, ‘hello dada!\r\n’]
#readline是读取一行内容,运行一次指针移动一次。
f3 =codecs.open('2.txt')
print(f3.readline())
print(f3.readline())
hello word!
hello dada!
#next是读取下一行内容
f3 =codecs.open('2.txt')
print(f3.readline())
print(f3.next())
f3.close()
hello word!
hello dada!
import codecs
f = codecs.open('3.txt','wb')
f.write('hello word\n')
print f.tell()
f.writelines(['aa\n','bb\n'])
print f.tell()
f.seek(0)
f.write('this is frist yyyyyyyyy')
f.flush()
print(f.name)
print(f.encoding)
print(f.mode)
print(f.closed)
f.close()
11
17
3.txt
None
wb
False
3.txt里面的内容为:
this is frist yyyyyyyyy
file中的with用法
import codecs
with codecs.open('1.txt') as fd:
print(fd.read())
print (fd.closed)
11
23
aa
bb
True
#打印文件的下标和内容:
with codecs.open('1.txt') as fd:
for line,value in enumerate(fd):
print (line,value)
if line == 3:
print (value)
0, ‘11\r\n’)
(1, ‘23\r\n’)
(2, ‘aa\r\n’)
(3, ‘bb’)
bb
#根据文件行数打印内容
import linecache
count =linecache.getline('1.txt',4)
print(count)
bb