file文件操作

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的字符串换成AA
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')
#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)
#关闭返回值,关闭就为true
print(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 linecache
count =linecache.getline('1.txt',4)
print(count)

bb

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值