老男孩python全栈就业班第9期第1部分基础+模块+面向对象+网络编程第9天-复习
复习
文件处理
打开文件
open('路径','打开方式','指定编码方式')
打开方式 r w a r+ w+ a+ b
r+ 打开方式直接写和读完再写
编码方式 ---- utf-8
操作文件
读
read 一次性读
readlines 一次性读
readline 一行一行读
不知道在哪儿结束
视频 图片 都用 rb 打开 bytes 按照字节读
for 循环 ———— 最好的方式!!!
with open(filename, 'r') as flie:
for line in file:
....
或者
自己补充
模块:linecache,这个模块也可以解决大文件读取的问题,并且可以指定读取哪一行
# 输出第2行 text = linecache.getline(filename, 2)
或者
自己补充
def readInChunks(fileObj, chunkSize=4096):
"""
Lazy function to read a file piece by piece.
Default chunk size: 4kB.
"""
while 1:
data = fileObj.read(chunkSize)
if not data:
break
yield data
f = open('bigFile')
for chuck in readInChunks(f):
#do_something(chunk)
f.close()
写
write
文件指针(教学使用名称叫光标)
seek 指定文件指针移动到某个位置
tell 获取文件指针当前的位置
truncate 截取文件
关闭文件
close
修改文件
文件是不能修改,可以如下处理
# log1文件内容:"班主任:星儿"
with open('log1', encoding='utf-8') as f1, open('log2', 'w', encoding='utf-8') as f2:
for line in f1:
if '星儿' in line:
line = line.replace('星儿', '啊娇')
#写文件
f2.write(line)
#删除文件和重命令文件
import os
os.remove('log1')
os.rename('log2', 'log1')
posted on 2019-12-22 10:28 herisson_pan 阅读(7) 评论(0) 收藏 举报
浙公网安备 33010602011771号