python之路--(文件操作)

1.只读模式'r'

a=open('d:\你好.txt',encoding='gbk',mode='r')  #只读模式下,以编码的方式显示。
content=a.read()
a.close()
print(content)

2.只读模式'rb'

a=open('d:\你好.txt',mode='rb')  #只读模式下,以字节的的方式显示。
content=a.read()
a.close()
print(content,type(content))

3.只写模式'w

a=open('d:\你好.txt',encoding='gbk',mode='w')   #只写模式,以编码方式显示。
content=a.write('美女')
a.close()

4.只写模式'wb'

a=open('d:\你好.txt',mode='wb')     #只写模式,
content=a.write('沙比'.encode('utf-8'))#确定书写的编码的方式
a.close()

5.追加模式'a'

a=open('d:\你好.txt',encoding='utf-8',mode='a')#追加模式,要确定追加内容的编码方式。
content=a.write('小黄')
a.close()

6.追加模式'ab'

a=open('d:\你好.txt',mode='ab')   #以字节形式追加
a.write(b'\x12')
a.close()

7.读写模式'r+'(在读写模式的情况下,如果是先读的话,就在最后在写入,如果是先写的话,文件里原来有内容,就会先写并且会覆盖书写长度相同的内容)

 

a=open('d:\你好.txt',encoding='utf-8',mode='r+')
content=a.read()
a.write('鲁班')
print(content)

8.在文件操作过程中,seek和tell的作用(seek指针中指的是字节的长度,tell的作用是确定当前指针的位置

a=open('d:\你好.txt',encoding='utf-8',mode='r+')
content=a.read(1)#读取第一个字符(read括号中读取的值字符的个数)
# a.seek(3)  #读取前三个字节,seek括号中表示的是读取的字节个数。
b=a.tell()    #tell表示读取当前指针的位置。
# a.write('李白')  #在读写模式下,先读的话就是读完后,在最后写,在先写的情况下, 就是在最开始先写,然后在读。当只写的时候,会覆盖内容。(不会全部覆盖)
# a.close()
print(b)

 

'

posted @ 2017-08-28 19:16  明-少  阅读(66)  评论(0)    收藏  举报