zoukankan      html  css  js  c++  java
  • python入门_老男孩_文件操作

      只写 

    # 只写
    # utf-8
    f = open('us', mode='w', encoding='utf-8')
    f.write('tonight, i can write down the most beautiful lines')
    f.close
    
    # bytes
    f = open('us', mode='wb') 
    f.write('如果可以'.encode('utf-8'))
    f.close()
    View Code

      

      写读

    # 读写
    f = open('us', mode='w+', encoding='utf-8')
    f.write('信念和勇气')
    print(f.read()) # 空白
    f.close()
    View Code

         光标定位

    # 读写
    f = open('us', mode='r+', encoding='utf-8')
    f.write('信念和勇气')
    f.seek(0)
    print(f.read())
    f.close()
    View Code

      

      只读

    # 只读
    f = open('us', mode='r', encoding='utf-8')
    content = f.read()
    print(content)
    f.close()
    
    f = open('us', mode='rb') # 以bytes方式,方便传输
    content = f.read()
    print(content, type(content))
    f.close()
    View Code

        按照字符开始读

    # 读写
    f = open('us', mode='r+', encoding='utf-8')
    f.write('信念和勇气')
    print(f.read(3))
    f.close()
    View Code

        按照字节定光标 / 前往后

    # 读写
    f = open('us', mode='r+', encoding='utf-8')
    f.write('新年贺卡')
    f.seek(3)
    print(f.read())
    f.close()
    View Code

        定光标 +  读 / 后往前

    # 定光标,读特定数目字符
    f = open('us', mode='r+', encoding='utf-8')
    f.write('新年贺卡恭喜发财')
    count = f.tell()
    f.seek(count-9)
    print(f.read(1))
    f.close()
    View Code

      读写

    # 读写
    f = open('us', mode='r+', encoding='utf-8')
    print(f.read())
    f.write('信念和勇气')
    f.close()
    View Code

      

    追加

    # 追加
    f = open('us', mode='a', encoding='utf-8')
    f.write('ZHAO')
    f.close()
    
    f = open('us', mode='ab')
    f.write('ZHAO'.encode('utf-8'))
    f.close()
    View Code

    推荐读写方式 

    with open('us', mode='r+', encoding='utf-8') as obj:
        obj.read()
        print(obj)
    
    # 打开多个文件
    with open('us', mode='r+', encoding='utf-8') as obj, open('us', mode='r+', encoding='utf-8') as obj1:
        obj.read()
        obj1.write('hello,world')
        print(obj)
    View Code

    用文件读写的方式登陆用户

    # 文件读写方式登陆用户,三次机会
    username = 'xiaozhao'
    password = '20181009'
    
    with open('us', mode='w', encoding='utf-8') as f:
        f.write('{}
    {}'.format(username,password))
    
        
    i = 0
    lis = []
    while i < 3:
        usr = input('请输入用户名:')
        pwd = input('请输入密码:')
    
        with open('us', mode='r', encoding='utf-8') as f:
            for k in f:
                lis.append(k)
        
        if usr == lis[0].strip() and pwd == lis[1].strip():
            print('登陆成功')
            break
        else:
            print('登陆失败')
                
    View Code

  • 相关阅读:
    4. Dictionary HashTable
    5.1. ISet HashSet
    5.2.ISet SortedSet
    6.1. String
    6.2. Encoding
    2.1. List
    1. 基础类型
    0.源代码代码分布情况
    0.2.比较接口Default
    Android获取应用启动时间
  • 原文地址:https://www.cnblogs.com/dignity/p/9756769.html
Copyright © 2011-2022 走看看