打开文件方式
r 只读方式,读取字符串 w 只写入方式,新写入内容覆盖旧的内容,写入字符串 a 追加写入的方式,写入字符串 rb 只读二进制方式,读取字节数据 wb 写二进制方式,写入字节数据 ab 追加二进制方式,追加写入字节 r+,读写方式,读取后,可在光标处写入,共用一个光标 w+,写读方式 a+,追加读方式
写入一个文件
f = open("test.txt","w",encoding="utf-8")
f.write("my name is jack\n")
f.write("i am 23 years old\n")
f.close()
with open("test.txt","w") as f:
f.write("addr is China")
读取一个文件
f = open("test.txt",'r',encoding="utf-8")
content = f.read()
line = f.readline()
lines = f.readlines()
part = f.read(100)
f.seek(n,0)
f.seek(n,1)
f.flush()
处理大文件
f2 = open("out.txt",'w')
with open("big_file.txt",'r') as f:
for line in f:
if 'xxx' in line:
line = line.replace("xxx","a")
f2.write(line)
f2.close()
练习
1. 抓取一张网络图片,保存在本地文件中 图片地址:https://wallpapertag.com/wallpaper/full/c/4/d/312839-dog-wallpaper-2880x1800-for-mobile.jpg
url = 'https://wallpapertag.com/wallpaper/full/c/4/d/312839-dog-wallpaper-2880x1800-for-mobile.jpg'
import requests
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36",
}
res = requests.get(url,headers=headers)
print(res.status_code)
with open("dog.jpg","wb") as f:
f.write(res.content)
2. 通过命令行方式传入参数,实现文件内容的替换 针对如下文件data.txt: My name is jack and my age is 23 i am from Chinese. His name is tom. He is 20 years old. Her name is lucy.
编写work.py 文件,实现如下方式的内容替换
python work.py name 姓名 data.txt
最终将data.txt中的“name” 都替换为"姓名",并打印替换了多少次。
3.模拟登录 模拟登录 程序运行时,打印出如下选项: 1.注册 2.登录 3.退出
a. 用户输入对应数字,实现注册、登录 b. 用户注册的信息存入一个users.txt文件中,格式如下, 张三,xxxxx,0 李四,xxxxx,3 … 其中名字必须唯一,xxx代表用户密码的hash加密,后面的数字是输入密码错误次数。 错误三次,则锁定账户 注册完成后,再循环打印 1.注册 2.登录 3.退出
c. 用户登录时,加载users.txt信息,查找当前输入的用户名是否存在, 输入的密码是否正确。均正确,则检查账号是否锁定,未锁定则进入内部系统(使用 一个循环模拟,用户输入什么就打印什么,输入exit退出循环)
否则,就提示"用户名或密码不正确",且用户名正确,密码不正确时记录一次错误, 并写入users.txt
d. 密码输错三次后,账号锁定,后续再登录则提示账号已锁定
参考答案
-
爬取图片,图片为字节数据,存入文件中 略 -
命令行方式,替换文件中的全局内容
import sys
work,old_str,new_str,filename = sys.argv
print(old_str,new_str,filename)
count = 0
with open(filename,'r+',encoding="utf-8") as f:
content = f.read()
while old_str in content:
content = content.replace(old_str,new_str,1)
count += 1
f.write(content)
print("替换后的内容:",content)
print("总共替换%d次"%count)
- 模拟登录
from hashlib import md5
print("欢迎使用用户登录系统")
f = open("users.txt","r+",encoding="utf-8")
content = f.readlines()
print("content:",content)
while True:
print("1.注册 2.登录 3.退出")
option = input("请输入选项:").strip()
if option == "1":
user = input("请输入用户名:").strip()
pwd = input("请输入密码:").strip()
exists = False
if content:
for i in content:
if user in i:
print("用户已存在")
exists = True
break
if not exists:
cur_user = ""
m = md5()
m.update(pwd.encode("utf-8"))
cur_user = "%s,%s,%d"%(user,m.hexdigest(),0)
cur_user += "\n"
content.append(cur_user)
f.write(cur_user)
f.flush()
print("注册成功!")
elif option == "2":
user = input("输入用户名:").strip()
pwd = input("输入密码:").strip()
user_right = False
account_lock = False
pwd_error = 0
for idx,i in enumerate(content):
if user in i:
user_right = True
while i.split(",")[1] != md5(pwd.encode()).hexdigest():
print("用户名或密码不正确")
pwd_error += 1
if pwd_error == 3:
print("账号已锁定")
account_lock = True
content[idx] = content[idx][:-2]+"%d\n"%pwd_error
f.seek(0,0)
f.writelines(content)
f.flush()
break
user = input("输入用户名:").strip()
pwd = input("输入密码:").strip()
if i[-2] == "3":
account_lock = True
print("账号已锁定")
if not account_lock:
print("欢迎进入图书系统")
print("退出with exit")
while True:
cmd = input("输入内容:")
if cmd != "exit":
print("你输入的:",cmd)
else:
break
elif option in ("3","exit","Exit","quit","Quit"):
print("程序退出")
break
elif option in ("help","?"):
print("帮助信息:\n")
print("输入1实现注册,输入2实现登录,输入exit则退出")
f.close()
? ? 上一篇:python之二进制 下一篇:
|