file文件操作

来源:互联网 发布:nba2k16捏脸中国人数据 编辑:程序博客网 时间:2024/06/05 14:57

file读操作

首先我们在本地项目里面创建一个1.txt,你的python脚本要和这个txt文件保持在同一个目录下
我们写入
11
23
aa
bb

#codecs这个模块主要解决文件乱码问题import codecs#打开文件需要几步:#1、open文件#2、文件操作(读或者写)#3、关闭文件f=codecs.open('1.txt')text = f.read()#将1.txt里面所有包含1的字符串换成AAresult = 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 codecsf = codecs.open('3.txt','wb')f.write('hello word\n')#tell 计算写入字符的个数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)#关闭返回值,关闭就为trueprint(f.closed)f.close()

11
17
3.txt
None
wb
False

3.txt里面的内容为:
this is frist yyyyyyyyy

file中的with用法

import codecs#利用with()来打开文件,脚本运行结束时会将脚本自动关闭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 linecachecount =linecache.getline('1.txt',4)print(count)

bb

#另外注意一下win下面的findstr相当于linux下的grep