python第五章:文件--小白博客

文件操作, 操作文件完毕后一定要记得close

# 读,默认是rt(文本的方式读取),rb模式是以字节读取

# 文件路径可以用3中形式表示
f = open(r'C:UsersfengziDesktopfirewalld.txt', 'rb')
f = open('C:\Users\fengzi\Desktop\firewalld.txt', 'rt', encoding='utf-8')
f = open('C:/Users/fengzi/Desktop/firewalld.txt', 'rt', encoding='utf-8')
f.read() #读取所有内容,光标移动到文件末尾
f.readline() #读取一行内容,光标移动到第二行首部
f.readlines() #读取每一行内容,存放于列表中
print(f.read().decode('utf-8'))
f.close()

# 写,默认是wt(文本的方式写入,覆盖写入

f.write('1111
222
') #针对文本模式的写,需要自己写换行符
f.write('1111
222
'.encode('utf-8')) #针对b模式的写,需要自己写换行符
f.writelines(['333
','444
']) #文件模式
例:
f = open('a.txt', 'w', encoding='utf-8')
f.write('申晨林是个好姑娘!
其实是假的!')#
是换行转译符
f.close()

# 以bytes类型写入文件(覆盖写入)
f = open('a.txt', 'wb')
f.write(b'111')
f.close()

# 追加append(不覆盖,添加内容)
f = open('a.txt', 'a', encoding='utf-8')
f.write('你好')
f.close()

# 修改
f = open('test.txt', 'r', encoding='utf-8')
data = f.read()
if '222' in data:
    result = data.replace('222', '111')
f.close()
f = open('test.txt', 'w', encoding='utf-8')
f.write(result)
f.close()


# 另一种打开文件的方式,利用上下文

with open('a.txt', 'r', encoding='utf-8') as f:
    print(f.read(3))
 

# 读取的类型

with open('a.txt', 'r', encoding='utf-8') as f:
    print(f.read(3))
    print(f.readline(3))#以行模式读取
    for i in f:
        print(i)
 

# 写入的类型

with open('a.txt', 'a', encoding='utf-8') as f:
    f.write('aaaa')
    f.writelines(['1','2','3','4'])#以列表的形式写入


#了解

f.readable() #文件是否可读
f.writable() #文件是否可读
f.closed #关闭文件
f.flush() #立刻将文件内容从内存刷到硬盘
f.name #查看打开的文件名

# 光标的移动(在文本模式seek前面的数字代表字符,字节模式seek前面的数字代表字节)
with open('a.txt', 'rb') as f:
    f.seek(0, 0)#等价于f.seek(0)  # 代表把光标移动到开头
    f.seek(2, 1)  # 代表在相对位置移动2个字节(1代表光标的相对位置,2代表在相对位置上把光标向后移动2个字节)
    f.seek(-3, 2)  # 代表在末尾往前移动3个字节(2代表把光标移动到末尾,-3代表把光标向前移动3个字节)
    f.read(3)#代表读取3个字符(意思是光标在第三个字节后面)
    print(f.read())


练习
#动态查看文件
#tail -f message

import time
with open('a.txt', 'rb') as f:
    f.seek(0,2)
    while True:
        data = f.readline()
        if b'404' in data:
            print(data.decode('utf-8'))
        else:
            time.sleep(0.5)

with open('a.txt', 'a', encoding='utf-8') as f:
    f.write('500')

#作业题答案 made in zhou

# 第一题
# 编写一个用户登录程序
# 1、登录成功显示欢迎页面
# 2、登录失败显示密码错误,并显示错误几次
# 3、登录三次失败后,退出程序
username = 'root'
password = '1'
count = 0
while count<3:
    a = input('name:')
    b = input('pswd:')
    if a==username and b==password:
        print('yes')
        break
    else:
        print('re')
        count+=1
        if count==3:
            print('out')
 
# 第二题
# 可以支持多个用户登录
# 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态
 
#(半成品)
info = { 'root':['root',0], 'zhou':['zhou',0], 'a':['a',0] } sys = [] sel = int(input('请选择1:登录,2:注册')) if sel==2: while True: name = input('请输入用户名:') sec = input('请输入新密码:') sec2 = input('再次输入密码:') if sec==sec2: print('用户注册成功') break else: print('两次密码不一致,重新输入') if name and sec: info = ['name',['sec',0]] # sys.append(info) with open('test.txt','a',encoding=('utf-8')) as h: h.write(' %s:%s ' %( info[0],info[1]))

#第一题答案
username = 'root'
password = 'root'
count = 0
print('请登录...')
while True:
    user = input('username:')
    pwd = input('password:')
    if user == username and pwd == password:
        print('欢迎登陆')
        break
    else:
        count += 1
        print('密码错误', count)
        if count == 3:
            print('')
            break

# 第二题答案

userinfo = {
    'root':['root',0],
    'fengzi':['fengzi',0],
    'test': ['test',0]
}

while True:
    with open('lock.txt', 'r', encoding='utf-8') as f:
        username = input('username:')
        if not username:
            continue
        elif username in f.read():
            print('您的账户已被锁定,请联系管理员')
        elif username in userinfo.keys():
            password = input('password:')
            if password in userinfo[username][0]:
                print('欢迎页面')
                break
            else:
                userinfo[username][1] += 1
                print('密码错误',userinfo[username][1])
                if userinfo[username][1] >= 3:
                    with open('lock.txt', 'a', encoding='utf-8') as f:
                        f.write('%s|' % username)
        else:
            print('用户名不存在')
 
原文地址:https://www.cnblogs.com/zhou2019/p/10574189.html