Python:文件操作

文件操作

1,文件路径:d:\xxxx.txt
    绝对路径:从根目录到最后
    相对路径:当前目录下的文件
2,编码方式:utf-8
3,操作方式:只读,只写,追加,读写,写读......
(1)只读--r
f =open('路径',mode='r',encoding='编码方式')
content=f.read()
print(content)
f.close() 
只读-r
以什么编码方式储存的文件,就要以什么编码方式打开。
只读:r----->以str方式读取
只读;  rb------>以bytes类型打开,用于非文字文件的打开.
(2)只写-->没有此文件就会创建文件。有个文件则会先将源文件的内容全部清除,再写。
只写:w
f =open('路径',mode='w',encoding='编码方式')
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('+7')
    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---》str:
1,decode(解码)
s1 = b.decode('utf-8')
2,如果字符串里都是字母
解码的时候写gbk并不会报错
s =abf
b=s.encode('utf-8')

print(b)

s1 =b.decode('gbk')

print(s1)

 
编码与解码

 

posted @ 2018-01-16 16:51  kakawith  阅读(431)  评论(0编辑  收藏  举报