python全栈闯关--8-文件操作

1、打开文件open

# 1、直接打开
open('account', mode='w', encoding='utf-8')
# 2、打开赋值给一个句柄
f = open('account', mode='r', encoding='utf-8')
f.close()
# 3、使用with打开,好处是可以不使用close
with open("account", mode='r', encoding='utf-8') as f1:
    pass

 文件可以是相对路径,也可以是绝对路径

2、文件读取模式

读r、r+、rb、r+b

直接读取:

f = open('account', mode='r', encoding='utf-8')
print(f.read())
f.close()

按照字符读取:

f = open('account', mode='r', encoding='utf-8')
print(f.read(3))  # 读取字符读取,读取3个字符b
f.close()

使用rb模式读取

f = open('account', mode='rb')  # 按照bytes读取,不需要指定字符集编码
print(f.read())  # 执行结果为bytes类型
f.seek(0)  # 跳到行首
print(f.read().decode('utf-8'))  # bytes转换为utf-8 使用decode
f.close()

rb模式读取到结果为bytes格式

bytes准换为字符串decode('格式')

字符串转换成bytes使用encode('格式'),如果是英文,可以使用b'berr'方式转换,包含中午必须使用encode

 

f = open('account', mode='r+', encoding='utf-8')
print(f.read())
f.write('this is bee honey')  # 先读,后写。读取到哪个位置,在哪个位置继续写
f.close()

f = open('account', mode='r+b')
print(f.read().decode('utf-8'))
f.write("write test\n".encode('utf-8'))  # 如果不进行编码,会报错:TypeError: a bytes-like object is required, not 'str'
f.writelines(['this is bee honey'.encode('utf-8'),
              '\nsecond line'.encode('utf-8')])
f.close()

 

 

读w、wb、w+、w+b

w模式

f = open('account', mode='w', encoding='utf-8')  # 写模式都是删除后,重新写入,不会在原有基础上添加
f.write('honey bee \n')
f.write(" bear big !\n")
f.write("beear two!")
f.close()

wb模式

f = open('account', mode='wb')  # 写模式都是删除后,重新写入,不会在原有基础上添加
f.write('honey bee \n'.encode('utf-8'))  # 需要写入的为bytes类型,否则报错
f.write(b" bear big !\n")  # b转换成bytes模式
f.close()

w+

f = open('account', mode='w+', encoding='utf-8')  # 写模式都是删除后,重新写入,不会在原有基础上添加
f.write('honey bee \n')  
f.write(" bear big !")  
f.seek(0)  # 指向文件开头,从头读取文件
print(f.read())
f.close()

w+和r+都是同时读和同时写,r+先读后写,不覆盖原始文件。w+直接删除原文件后,才进行写入,导致w+模式不常用,一般使用r+模式

f = open('account', mode='w+b')  # 写模式都是删除后,重新写入,不会在原有基础上添加
print(f.read())
f.write('honey bee \n'.encode('utf-8'))
f.write(" bear big !".encode('utf-8'))
f.seek(0)  # 指向文件开头,从头读取文件
print(f.read())
f.close()

追加 a、a+、ab、a+b

a模式,只能在文件结尾追加,但是不能读取

f = open('account', mode='a')  # 追加模式,文件结尾直接追加
# 只能写,不能读取
f.write('honey bee \n')
f.write(" bear big !")
f.close()

a+模式,可以读取,也可以追加

f = open('account', mode='a+')
# f.read()
f.write('honey bee \n')
f.write(" bear big !")
f.seek(0)
print(f.read())
f.close()

  ab模式,按照bytes型追加,只能追加,不能读取

f = open('account', mode='ab')
# f.read()
f.write('honey bee \n'.encode('utf-8'))
f.write(" bear big !".encode('utf-8'))
f.close()

a+b模式,可以按照bytes追加,同时可以使用seek调整位置后,读取,写入

f = open('account', mode='a+b')
f.read()
f.write('honey bee \n'.encode('utf-8'))
f.write(" bear big !".encode('utf-8'))
f.seek(0)
print(f.read())
f.close()

with模式,使用with模式打开文件,结束可以不必使用close函数

with open('account', 'r+', encoding='utf-8') as f:
    content = f.read()
    print(content)

练习:模拟注册、登录

username = input("请输入你的用户名:")
userpasswd = input("请输入你的密码:")

with open('account', 'w', encoding='utf-8') as f:
    f.write("{}\n{}".format(username, userpasswd))

print('注册成功!')

lis = []
try_count = 0

while try_count < 3:
    in_uname = input("请输入你的用户名:")
    in_pwd = input("请输入你的密码:")
    with open('account', encoding='utf-8') as f1:
        for line in f1:
            lis.append(line)
    if in_uname == lis[0].strip() and in_pwd == lis[1].strip():
        print("登录成功!")
        break
    else:
        print("账户或者密码错误!")
        try_count += 1

猜你喜欢

转载自www.cnblogs.com/zxw-xxcsl/p/11623305.html