• 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

  • 相关阅读:
    C#8.0新特性
    C#7.0新特性
    C#6.0新特性
    C#6.0到C#8.0的新特性
    纪念博客开通的6月29日
    什么是开发中经常说的'POCO'
    什么时候用Model,什么时候用Entity?
    C#数组的 Length 和 Count()
    C#中foreach的实现原理
    Windows Server 2012 R2远程桌面默认端口修改
  • 原文地址:https://www.cnblogs.com/dignity/p/9756769.html
Copyright © 2020-2023  润新知