文件操作 知识 习题 整理

文件操作:

    文件的读,写,添加以及判断文件编码形式

推荐用以下形式写:

with open('a.txt','w') as f:
    pass
 
with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
    data=read_f.read()
    write_f.write(data)

1.文件的读(只读):

      f = open('xx.txt', 'r', encoding = '编码形式(如utf-8)')  # 用什么形式编的码,就用什么形式读 否则会发生乱码

      data = f.read()

      print(data)  # 打印文件中的内容

      f.close()

2.文件的写(只写):

      f = open('xx.txt', 'w', encoding = '编码形式(如utf-8)')

      data = f.write()  # 创建(清空'xx.txt')及写入    注:只能写入 str

      print(data)  # 这里输出的是 write() 的 返回值(即所输入字节的长度)

      f.close() 

3.文件的读(读入二进制形式):

      f = open('xx.txt', 'rb')      # 因为读入文件中的二进制形式,不涉及编码问题

      f.read()

      f.close()

4.文件的写(写入二进制):

      f = open('xx.txt', 'wb')

      f.write('xx')    ## 这里的 'xx' 需写入 二进制码 即 0010 1100 或 ” fuck you ".encode("utf-8")形式

      f.close

5.文件的添加(在原有基础上写入):

      f = open('xx.txt', 'a', encoding = '编码形式(如utf-8)')

      f.write('xx')

      f.close()

6.文件的读写模式(既能读又能写):

      f = open('xx.txt', 'r+', encoding = '编码形式(如utf-8)')

      f.read()      #  因为是读写模式,只能先读再写

        f.write('xx')      

      f.close     

7.文件的写读模式(既能写又能读):

      

                    f = open('xx.txt', 'r+', encoding = '编码形式(如utf-8)')

      f.read()      #  因为是写读模式,只能先写再读

        f.write('xx')      ###注意:由于先写再读,写是创建即清空原先‘xx.txt'里的内容,所以基本不用这个

      f.close     

8.文件编码形式的确认:

      import  chardet

      f = open('xx.txt','rb')

      data = f.read()

      f.close

      result = chardet.detect(data)

      print(result)

 9.tell():

      s.tell()   # 即返回当前光标所在位置(即字节位置)##注:在next()调用中,使用tell 会报错

10.seek():

      s.seek(x) # 把光标移动到x位置,x即字节这里按字节走

11.flush():

      s.flush() # 强制把当前写入转入进硬盘

12.readline():

      s.readline #只读取出一行

9.练习(编码和文件处理):

    

i.请说明python2 和 python3 的默认编码

      pyhton2 默认编码为 gbk

      python3 默认编码为 utf-8

ii.为什么会出现中文乱码?请列举乱码原因

      

      用a种解码方式,打开b种码

      

  

原文地址:https://www.cnblogs.com/christmassa/p/9010688.html