zoukankan      html  css  js  c++  java
  • python基础===文件对象的访问模式,以及计数循环的使用方法

    案例一:

    一个几M的文本文件,需要每隔100行写到新的文件中。

    代码实现如下:

    with open(r'f:ook.txt','rb') as f1:
        with open(r'f:ook2.txt','wb') as f2:
            i = 0
            for line in f1:
                i+=1
                if i % 33 ==0:
                    f2.write(line)
    

     这里补充一个知识点:

    文件对象的访问模式

    文件模式 操作
    r  以读方式打开
    w 以写的方式打开(必要时会清空)
    r+ 以读写模式打开
    w+ 以读写模式打开(必要时会清空)
    a 以追加模式打开,不会清空。(必要时创建新文件)
    a+ 以读写模式打开,不会清空。(必要时创建新文件)
    ab 以二进制追加模式打开,不会清空。(必要时创建新文件)
    ab+ 以二进制读写模式打开。(必要时创建新文件)
    rb+ 以二进制读写模式打开
    rb 以二进制读模式打开
    wb 以二进制读写模式打开(必要时会清空)

    在执行上面代码的时候,如果以r或者w的模式打开。会报错:

      File "C:/Users/yangbo/Desktop/计数循环.py", line 4, in <module>
        for line in f1:
    UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 18: illegal multibyte sequence

    所以,必须以二进制模式打开!

    案例二:

    请问一个日志文本文件有2000行,我要提取其中的100行到200行,怎么做?

    with open(r'f:ook.txt','rb') as f1:
        with open(r'f:ook2.txt','wb') as f2:   #以二进制追加模式打开!如果没有book2.txt文件,新建一个
            i = 0
            while True:
                line = f1.readline()
                i += 1
                if i>100 and i<200:
                    f2.write(line)
                if i>200:
                    break
                if not line:                  
                    break
                
    


  • 相关阅读:
    如何使用Dev C++调试(debug)c程序
    C内存对齐详解
    epics commands
    #include <errno.h>
    linux中tail命令
    source env then start eclipse
    c++ constructor with para
    如何访问虚拟机中的架设的Web服务器(解决方法)
    dcss_gui_handler
    atlsoap.h”: No such file or directory
  • 原文地址:https://www.cnblogs.com/botoo/p/7388576.html
Copyright © 2011-2022 走看看