文件操作方法

文件路径:d:\zzz\xxxx.txt,一定注意光标问题!!!seek(),写完光标在最后要往前提

    1、绝对路径:从根目录到现在目录
    2、相对路径:当前目录下的文件,同级
2,编码方式:utf-8
3,操作方式:只读,只写,追加,读写,写读
(1)只读--r
f.read()
以什么编码方式储存的文件,就要以什么编码方式打开。
只读:r转换为str方式读取
只读;  rb以bytes类型打开,用于非文字文件(图片,pdf)的打开.
(2)只写没有此文件就会创建文件。有个文件则会先将源文件的内容全部清除,再写。
只写:w
f =open('文件路径',mode='w',encoding='编码方式(一般为utf-8或则gbk)')
content=f.write('内容')
f.close() 
wb:
f =open('文件路径',mode='wb')
content=f.write('内容'.encode('utf-8'))
f.close()
 
(3)追加在文件后追加内容:a
f =open('文件路径',mode='a',encoding ='编码方式')
f.write('内容')
f.close()
 
ab
f =open('文件路径',mode='a')
f.write('内容',encode('utf-8'))
f.close()
(4)r+(先读后写)
读写:
f = open('log',mode ='r+',encoding='utf-8')
content =f
print(f.read())
f.write('内容') 
f.close()
(5)写读:(先写后读)
f = open('log',mode ='r+',encoding='utf-8')
content =f
f.write('内容') 
print(f.read())
f.close()
先写后读。先写,光标从开头往后走,覆盖后边的内容。
(6)r+模式的bytes类型:r+b
f = open('log',mode ='r+b')
print(f.read())
f.write('内容'.encode('编码方式'))
f.close()
(7)w+
f =open('文件路径',mode='w+',encoding ='utf-8')
f.write('内容')
print(f.read())
f.close()
4、seek:调光标
f.seek(位置)-----》f.seek(0)
'''
read是按字符来读。
seek是按字节去定光标的位置
'''
f =open('log',mode = 'r+',encodeing='utf-8')
f.seek(3)
content =f.read()
print(content)
f.close()
5、电影中下载断点续传方法,即定位光标的位置
  f.tell()定位光标的位置
    f =open('log',mode = 'a+',encoding ='utf-8')
    f.write('a')
    count =f.tell()
    f.seek(count -9)#在utf-8中一个中文占三个字节
    print(f.read())
    f.close()
6、f.readable()
判断是不是可读返回值true或false
line =f.readline()
print(line)
f.close()
 
7、redline
一行一行读
line = f.readlines()
print(line)
f.close()
 
每一行当成列表中的一个元素,添加到列表中(lines是列表)
truncate
截取一段去读
8、用with打开文件
with open('文件路径',mode='r',encoding='utf-8') as obj:
    print(obj.read())
打开多个文件
编码二
bytes转换为ustr:
1,decode(解码)
s1 = b.decode('utf-8')
2,如果字符串里都是字母
解码的时候写gbk并不会报错
posted @ 2017-12-25 22:47  Ebola  阅读(197)  评论(1编辑  收藏  举报