python基础八---文件操作


1、文件操作
  XXXXX.txt
    1.文件路径:d:XXXXX.txt(绝对路径)
    2.编码方式:utf-8    gbk
    3.操作方式:只读、只写、追加、读写、写读....
    
排错:
以什么编码方式储存的文件,就以什么编码方式打开。
如果系统默认不显示后缀名,路径文件不加后缀
相对路径下的操作:
只读:r、rb
r模式:
  f = open('motezhufu',mode='r',encoding = 'utf-8')
      content = f.read()
      print(content)
      f.close()
View Code
rb模式:(bytes类型:不需要加编码方式,用于非文字类文件及上传下载)
f = open('motezhufu',mode='rb')
content = f.read()
print(content)
f.close() 
View Code
只写: 没有该文件会创建文件。有文件会先把源文件清除,再将内容写入。
w模式:
f = open('motezhufu',mode='w',encoding = 'utf-8')
content = f.write()
print(content)
f.close()
View Code
wb模式:(bytes类型:不需要加编码方式,需要".encode('编码方式')"指正)
f = open('motezhufu',mode='wb',)
content = f.write('XXX'.encode('编码方式'))
print(content)
 f.close()   
View Code
追加:追加在有文字的最后一位。
a模式:
 f = open('motezhufu',mode='r',encoding = 'utf-8')
 content = f.write('内容')
 print(content)
 f.close()
View Code
 ab模式(bytes类型:不需要加编码方式,需要".encode('编码方式')"指正)
f = open('motezhufu',mode='r',encoding = 'utf-8')
content = f.write()
print(content)
f.close()
读写:r+、r+b
r+模式
  先读后写;先把源文章读出来,再在最后追加
            先写后读;从头开始写,写多少位占多少位,没占的位会被读出来,都占位返回空
            # f = open('log',mode='r+',encoding='utf-8')
            # print(f.read())
            # f.write('大猛,小孟')
            # f.close()
View Code
r+b模式 读写(以bytes类型)
 f = open('log',mode='r+b')
 print(f.read())
 f.write('大猛,小孟'.encode('utf-8'))
 f.close()
View Code
写读:w+模式 : 先清除再写入
f = open('log',mode='w+',encoding='utf-8')
f.write('aaa')
f.seek(0)
print(f.read())
f.close()
追加+读:a+
f = open('log',mode='a+',encoding='utf-8')
f.write('佳琪')
count = f.tell()
f.seek(count-9)
print(f.read(2))
f.close()
2、功能详解(以r+为例)
   obj = open('log',mode='r+',encoding='utf-8')
        content = f.read(3)  # 读出来的都是字符
        f.seek(3)  # 是按照字节定光标的位置
        f.tell() 告诉你光标的位置
        print(f.tell())
        content = f.read()
        print(content)
        f.tell()
        f.readable()  # 是否刻度
        line = f.readline()  # 一行一行的读
        line = f.readlines()  # 每一行当成列表中的一个元素,添加到list中
        f.truncate(4)
        for line in f:
          print(line)
        f.close()

3、编码

#str --->byte encode 编码
s = '二哥'
b = s.encode('utf-8')
print(b)
#byte --->str decode 解码
s1 = b.decode('utf-8')
print(s1)
原文地址:https://www.cnblogs.com/TheLand/p/8110850.html