Python基础入门(六)
一、本节目标
- 掌握文件的概念和操作:文本文件、CSV文件
- 综合案例:奖励富翁系统、汽车租聘系统
二、文件介绍
- 文件是计算机中用于存储数据的一种载体,一般存储在磁盘上
- 文件通过以一定的格式和结构存储数据,可以包含文本、图像、音频、视频等各种类型的信息
- 文件在计算机中起着非常重要的作用,是信息传递和存储的基本单位
- 在程序中,我们把文件一般分为两类,一类是程序文件,一类是数据文件
三、open函数介绍
- open()函数用于打开一个文件,并返回文件对象
- 使用open()方法一定要保证关闭文件对象,即调用close()方法
- open()函数常用形式是接收两个参数:文件名(file)和模式(model)
- open(file, model = ‘r|w|a’)
四、读写文件-1
print(r"C:/Users/23077/Desktop/作业/张贺猛-7.11-预习笔记.docx")
file = open(r"C:\Users\23077\Desktop\作业\test01.txt", "r", encoding = 'utf-8')
lines = file.read()
print(lines)
file.close()
file = open(r".\data\readme.txt", "r", encoding = 'utf-8')
lines = file.readline()
while lines != '':
print(lines, end='')
lines = file.readline()
file.close()
file = open(r".\data\readme.txt", "r", encoding = 'utf-8')
lines = file.readlines()
print(lines, end='')
file.close()
五、读写文件-2
file = open(r".\data\readyou.txt", "w", encoding = 'utf-8')
file.write("w343\n")
file.write("233\n")
file.write("你们好\n")
file.close()
file = open(r".\data\readyou.txt", "a", encoding = 'utf-8')
file.writelines(("54\n", "233\n", "4322\n"))
file.close()
file = open(r".\data\readyou.txt", "r", encoding = 'utf-8')
lines = file.read()
print(lines, end='')
file.close()
with open(r".\data\readyou.txt", "r", encoding = 'utf-8') as file:
content = file.read()
print(content)
line = file.readline()
while line != '':
print(line, end='')
line = file.read.readline()
lines = file.readlines()
print(lines)
for line in file.readlines():
print(line, end='')
with open("data/readme.txt", "w", encoding = 'utf-8') as file:
file.writelines(['abc\n', '212\n', '一二三\n'])
六、练习
- 通过键盘输入自己的姓名,性别,年龄,爱好
- 通过write()函数记录到文本文件中
- 通过open()函数读取并显示在控制台
# 练习
person = []
for i in range(1):
name = input("请输入你的姓名:")
sex = input("请输入你的性别:")
age = input("请输入你的年龄:")
fav = input("请输入你的爱好:")
person.append(name+",")
person.append(sex+",")
person.append(age+",")
person.append(fav)
person.append("\n")
# person = [name, sex, age, fav]
with open(r"./data/person.txt", "a", encoding = 'utf') as file:
file.writelines(person)
with open(r"./data/person.txt", "r", encoding = 'utf') as file:
lines = file.readline()
while lines != '':
fields = lines.split(",")
print(f"姓名:{fields[0]}")
print(f"性别:{fields[1]}")
print(f"年龄:{fields[2]}")
print(f"爱好:{fields[3]}")
print("*"*20)
lines = file.readline()
七、CSV模块-读
import csv
with open("./data/test.csv", 'r') as file:
reader = csv.reader(file)
next(reader)
print("姓名\t性别\t年龄")
for row in reader:
print(f"{row[0]}\t{row[1]}\t{row[2]}")
八、CSV模块-写
import csv
with open("./data/test.csv", 'a', encoding= 'utf-8') as file:
writer = csv.writer(file, lineterminator = "\n")
writer.writerow(["mike", "male", "23"])
writer.writerow(([
["make", 'female', '22'],
["tom", "male", '23']
]))
with open("./data/test.csv", 'r') as file:
reader = csv.reader(file, delimiter=';') # 指定分隔符
next(reader)
print("姓名\t性别\t年龄")
for row in reader:
print(f"{row[0]}\t{row[1]}\t{row[2]}")
九、练习
- 通过键盘输入多名学生的学号,姓名,性别,年龄
- 记录到CSV文件
- 读取CSV文件并显示在屏幕上
import csv
with open("./data/students.dat", "a", encoding = 'utf-8') as file:
while True:
id = input("请输入你的学号:")
name = input("请输入你的姓名:")
dex = input("请输入你的性别:")
age = input("请输入你的年龄:")
data = [id, name, dex, age]
writer = csv.writer(file, lineterminator = '\n')
writer.writerow(data)
ret = input("是否继续(y/n)?")
if ret.lower() != 'y':
break
print("文件保存成功!!")
with open("./data/students.dat", "r", encoding = 'utf-8') as file:
reader = csv.reader(file, delimiter = ",")
print("学号\t姓名\t性别\t年龄\t")
for row in reader:
print(f"{row[0]}\t{row[1]}\t{row[2]}\t{row[3]}")
十、综合练习-1
- 奖客富翁系统
- 需求描述:
- 某商场要求开发一套奖客富翁系统,要求客户注册成为商场会员,登录之后,就可以参加抽奖活动
- 主要功能是有会员注册、登录和抽奖
- 抽奖采用随机数random.randit(a, b)表示“中奖”和“未中奖”
# 项目一
# 用户注册
import random
users = {}
logined = False
def register():
print("********用户注册*******")
name = input("请输入用户名:")
if name in users:
print("用户名已存在")
return
pwd = input("请输入密码:")
users[name] = pwd
print("注册成功!")
# 登录
def login():
print("********用户登录*******")
name = input("请输入用户名:")
if name not in users:
print("用户不存在")
return
pwd = input("请输入密码:")
if users[name] != pwd:
print("密码错误")
return
print(f'欢迎{name}登录!')
global logined
logined = True
# 抽奖
def prize():
if not logined:
login()
pc = random.randint(0, 1)
if pc == 0:
print("很遗憾,您没有中奖-_-")
else:
print("~恭喜,您中奖了~")
def start():
while True:
print("*"*30)
print("1.注册")
print("2.登录")
print("3.抽奖")
print("4.退出")
print("*"*30)
n = int(input("请选择以上功能号【1-4】:"))
match n :
case 1 :
register()
case 2:
login()
case 3:
prize()
case 4:
break
case _:
print("输入错误")
print("~程序结束~")
start()
十一、综合练习-2
- 汽车租聘系统
- 需求描述
-------------
# 租车系统 #
2.添加车牌号
3.显示所有的车牌号
4.查找车牌号
5.退出系统
-------------
请选择功能:
def func1():
print("*" * 30)
print('# 租车系统 #')
print('1.添加车牌号')
print('2.显示所有车牌号')
print('3.查找车牌号')
print('4.删除车牌号')
print('5.退出系统')
print("*" * 30)
lists = []
def func2(lists):
n = input("请输入要添加车牌号的个数:")
for i in range(int(n)):
list = input(f"请输入第{i+1}个车牌号:")
lists.append(list)
def func3():
for i in range(len(lists)):
print(lists[i])
def func4():
idcode= input("请输入要查找的车牌:")
if idcode in lists:
print("恭喜,已查找到车牌!")
else:
print("对不起,找不到车牌号!")
def func5():
se_code = input("请输入要删除的车牌号:")
lists.remove(se_code)
print("删除成功!!")
func1()
while True:
code = int(input("请选择功能:"))
match code:
case 1:
func2(lists)
case 2:
func3()
case 3:
func4()
case 4:
func5()
case 5:
break
case _:
print("输入不合法,请重新输入!")
print("程序结束!")
十二、总结
- 掌握函数的定义及调用,参数传递,返回值
- 掌握简单算法的使用:冒泡排序法、杨辉三角形
- 掌握文本文件和CSV文件的读写操作