zoukankan      html  css  js  c++  java
  • python文件的基本操作

    打开文件的三种方式:
      open(r'E:学习日记pythoncode文件的简单操作.py')
      open('E:\学习日记\python\code\文件的简单操作.py')
      open('E:/学习日记/python/code/文件的简单操作.py')
    #字符串前面加一个r代表原生的raw
    # rt,wt,at:r读,w、a写,t表示以文本打开

    eg:
    >>> res = open(r'E:	est.txt','r',encoding='utf-8')
    >>> read = res.read()
    >>> print(read)
    >>> res.close()
    123
    小米
    qwe
    asd

    #文本形式读取

    with open(r'E:	est.txt','rt',encoding='utf-8') as f:
    
    #read(1)代表读取一个字符,读取光标往右的内容(默认光标在开头)
      data1 = f.read(1)
      print(data1)
      data2 = f.read(1)
      print(data2)
    1
    2
    
    #readline:按行读取
      data1 = f.readline()
      data2 = f.readline()
      print(data1)
      print(data2)
    123
    小米
    
    #readlines:把内容以列表形式显示
      data = f.readlines()
      print(data)
    ['123
    ', '小米
    ', 'qwe
    ', 'asd']
      for a in data:
      print(a)
    123
    
    小米
    
    qwe
    
    asd
    
    #readable:是否可读(返回布尔类型)
      res = f.readable()
      print(res)
    True

    #文本形式写
    #w:覆盖写
    #a:追加写

    with open(r'E:	est.txt','wt',encoding='utf-8') as res:
    #write:往文件里覆盖写入内容
      res.write('谢谢你的爱1999')
    谢谢你的爱1999(test.txt)
    
    #writelines:传入可迭代对象变成字符串写入文件
      res.writelines(['qw','
    12','3er'])
      res.writelines({'name':'小米','age':23})
    helloqw
    123ernameage
    
    with open(r'E:	est.txt','at',encoding='utf-8') as res:
    #a模式write写入为追加
      res.write('
    456')
    helloqw
    123ernameage
    456
    
    #writable:是否可写
      res.writable()
    True 

    #rb,wb,ab
    #bytes类型读

    with open(r'E:	est.txt','rb') as res:
      a = res.read()
      print(a)
    b'hello
    xe4xbdxa0xe5xa5xbd'
      print(a.decode('utf-8'))
      hello
    你好

    # bytes类型写:
    #1.字符串前面加b(不支持中文)
    # 2.encode

    with open(r'E:	est.txt', 'wb') as res:
      res.write(b'asd')
    asd
      res.write('你好'.encode('utf-8'))
    你好 

    #光标的移动

    with open(r'E:	est.txt', 'wb') as res:
    #前面的数字代表移动的字符或字节,后面的数字代表模式(0:光标在开头,1:代表相对位置,2:代表光标在末尾)
      res.seek(2,0)
      print(res.read())
    e
    qwertyuiop
      res.seek(1,0)
      res.seek(2,1)
      print(res.read().decode('utf-8'))
    qwertyuiop
      res.seek(-3,2)
      print(res.read().decode('utf-8'))
    iop 

    # tail -f /var/log/message | grep '404'

    小练习: 

      # 编写一个用户登录程序
       登录成功显示欢迎页面
       登录失败显示密码错误,并显示错误几次
       登录三次失败后,退出程序

     作业升级:
       # 可以支持多个用户登录
       # 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态

  • 相关阅读:
    .NET的DTO映射工具AutoMapper
    使用TeamCity对项目进行可持续集成管理
    SpecFlow
    重构--改善既有代码的设计
    EntityFramework 7 开发纪录
    Solr索引
    DDD分层架构之值对象(层超类型篇)
    C#异步Socket示例
    Cnblogs API
    白鸦三次创业反思:公司遇问题 怎么走都对(转)
  • 原文地址:https://www.cnblogs.com/twoo/p/11655002.html
Copyright © 2011-2022 走看看