文件读取与修改

二周五次课(10月27日)

##6.1 读取文件内容

打开文件需要几步

1、 open文件
2、 文件操作(读或者写)
3、 关闭文件

实践操作 f.read() codecs.open()

当前目录下有一个text.txt文件,内容如下

	 11111
	 22222
	 33333
	 44444
	 55555

编写一个text.py 文件内容如下

import codecs
f = codecs.open('text.txt')
print(f.read())
f.close()

运行text.py就可以读取test.txt文件,读出的形式为str

test = f.read()
print(type(test))

str

codecd.open()

这个类用于解决文件乱码的问题

##6.2 写入一个新的文件

open(filename,mode)

mode 有几个参数需要注意

r 读
w 写
b 二进制
a 追加

举例

import codecs

f=codecs.open('2.txt','w')
f.write('Hello world \n')
f.write('Hello {0} \n'.format('Earth'))
f.write('Hello %s \n' %'Human')
f.close()

##6.3.1 文件操作的常用方法

readline()

将每一行读取为一个字符串,并放到一个列表里

f = open('2.txt','rb')
print(f.readlines())
f.close()

输出

['Hello world \r\n', 'Hello Earth \r\n', 'Hello Human \r\n']

####打指定行

f = open('2.txt','rb')
print(f.readlines()[0])   //打印第一行
print(f.readlines()[1])   //打印第二行
f.close()

注意,f读取的时候光标只能顺序读取,不能向上跳回,所以如果先打印第二行在打印第一行,或者打印全文后在打印第一行都会报错。

readline() 打印一行

f = open('2.txt','rb')
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

输出

Hello world

Hello Earth

Hello Human

write() 传入一个字符串 writelines 传入一个序列

import codecs
f = codecs.open('3.txt','wb')
f.writelines(['111','222','333'])
f.close()

##6.3.2 Codecs的特殊使用

tell ()

查看字符串长度

import codecs

f = codecs.open('3.txt', 'wb')
f.writelines(['111\n', '222', '333'])
print(f.tell())
f.close()

输出

10 (/n 是一个字符)

seek() 移动光标到某位,seek(0) 为初始位

import codecs

f = codecs.open('3.txt', 'wb')
f.writelines(['123456789'])
f.seek(0)
f.write('insert')
f.close()
f.open('3.txt','rb')
print(f.read())
f.close()

输出

insert789	

flush() 将文件的缓存刷到内存中

f.name f.closed

f.name 文件名
f.closed 检测文件是否关闭,若关闭返回true,未关闭返回false
f.encoding
f.mode

>>> f = open('3.txt','w')
>>> print(f.name)
3.txt
>>> print(f.encoding)
None
>>> print(f.mode)
w
>>> print(f.closed)
False
>b>> f.close()
>>> print(f.closed)
True
>>>

##6.4 With的特殊用法

有时候,我们在编码的时候可能忘记关闭文件,而太多文件没有关闭会对系统造成压力,with就可以让我们不用文件的时候自动关闭文件。

import codecs

with codecs.open('3.txt','rb') as f:
    print(f.closed)
print(f.closed)

返回

False
True
enumerate
>>> import codecs
>>>
>>> with codecs.open('3.txt','rb') as ff:
...     for line,value in enumerate(ff):
...         print(line,value)
...         if line == 4-1:
...             print(value)
...
(0, '1\r\n')
(1, '2\r\n')
(2, '3')
>>>
linecache

输出3.txt的第2行

import linecache

count = linecache.getline('3.txt',2)
print(count)	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值