zoukankan      html  css  js  c++  java
  • 文件操作

    open(filename,model,encode)

    f=open('log.txt')

    data=f.read()

    f.close()

    print(data)

    read(num):若为普通打开方式,num为读取指定数目字符的个数

    模式:

    r:只读模式

    w:只写模式,不存在则创建,存在则清空

    x:只写模式,不存在则创建,存在则报错

    a:追加模式,不存在则创建,存在则追加内容

    以字节方式打开:

    f=open("log.txt","r",encoding="utf-8"),读取二进制的数据,以 encoding的编码方式转换成字符串

    f=open("log.txt","rb")

    普通方式打开时,python内部自动将字节数据转换成字符串了

    写数据

    f=open("log.txt","wb")

    f.write(bytes("姓名",encoding="utf-8")):手动进行转换成字节

    f.close()

    “+”表示可以同时读写某个文件:r+,w+,x+,a+

    seek():移动文件指针的位置

    tell():返回文件指针的位置

    w+:先清空,在写的之后,就可以读了,使用seek(0),将指针移动到原点

    x+:如果文件存在,则报错

    a+:追加,只在最后追加,seek()对于写不管用

    r+:

      读,从0开始读取

           写,先读,最后追加

                  主动seek,写从当前指针向后写

                  如果不读便开始写,从最开始插入数据,如果有数据,则覆盖

           write()和read()各自维护各自内部的指针

    刷新函数:flush()

    判断是否可读:readable()

    仅读取一行数据:readline()

    readlines:将每一行元素都读取返回为一个列表

    截取数据:truncate(),截取从指针往前的所有数据

    按行循环读取数据:

    f=open("ha.log",'r',encodeing="utf-8")
    for line in f:
        print(line)

    避免显示关闭文件的用法

    with open("log.txt") as f:
    f.read()

    文件操作的应用:系统登录时读取相关文件进行用户名和密码的校验

    line.strip():默认可以将换行符也去掉

    python2.7之后,with关键字支持同时打开两个文件

    with open("log1.txt") as f1,open("log2.txt") as f2:    
    f1.read()
    f2.read()
  • 相关阅读:
    Nim or not Nim? hdu3032 SG值打表找规律
    Maximum 贪心
    The Super Powers
    LCM Cardinality 暴力
    Longge's problem poj2480 欧拉函数,gcd
    GCD hdu2588
    Perfect Pth Powers poj1730
    6656 Watching the Kangaroo
    yield 小用
    wpf DropDownButton 源码
  • 原文地址:https://www.cnblogs.com/lvjygogo/p/8510186.html
Copyright © 2011-2022 走看看