第五章 文件
5.1 文件的打开和关闭操作
打开一个当前目录下的文件,进行简单的操作后,关闭这个文件
paper = open('first', 'x')
paper.write("Welcome to Python File World!")
paper.close()
paper2 = open('first', 'r')
hello = paper2.readline()
print(hello)
知识点:
- open()函数打开模式
- 打开文件后记得关闭文件
5.2 文件的读写操作
文本文件的读写是按照字符串方式进行,二进制文件的读写是按照字节流进行
例 5.2 新建一个文件,并向文件内写入几行数据,写完后重新定位读写指针位置到文件的开头,输出全部文件的内容
paper = open('first', 'w+')
print(paper.read())
paper.write('Welcome to Python File World!\r\n')
paper.write('Python is very powerful!\r\n')
paper.write('Python is also interesting!\r\n')
print(paper.read())
paper.seek(0)
print(paper.read())
paper.close()
知识点:
- 文件的读写方法
5.3 文本文件操作
例 5.3 读取一个记录了用户信息(账号和密码)的文本文件,用户信息包括账号名和密码两部分,文本中每行记录一条用户信息,账号和密码之间用空格隔开,查找文件是否存在一个账户名为 hello 的账号,如存在将其密码修改为 123456;若不存在,则在文件尾部追加一个 hello 账户信息,并设定密码为 123456.
print("文本内原始信息: ")
with open('User.txt', 'r', encoding='utf-8') as f:
userlist = []
for line in f.readlines():
print(line.strip('\n'))
user = line.strip('\n').split(' ')
userlist.append(user)
flag = 0
for item in userlist:
if item[0] == "hello":
item[1] == "123456"
flag = 1
if flag == 0:
newUser = ["hello", "123456"]
userlist.append(newUser)
print("修改后文本信息: ")
with open('User.txt', 'w', encoding='utf-8') as f_w:
for item in userlist:
f_w.write(item[0]+" "+item[1]+'\n')
print(item[0]+" "+item[1])
if flag == 1:
print("hello用户已存在,密码已修改!")
else:
print("hello用户不存在,已创建此用户")
5.4 CSV 文件的读写
例 5.4 有一个存放学生信息的文件 student.csv,存有五名学生的学号、姓名、成绩信息,读取并显示文件内容,计算学生成绩的平均值,根据学生的成绩进行排序,并将排序后的结果写入新文件 student123.csv 中
student_xy = []
print("原文件的内容是:")
with open('student.csv', 'r', encoding='gb18030') as data:
for line in data:
print(line.strip())
line = line.strip()
student_xy.append(line.split(','))
print("转换成列表后是: ")
print(student_xy)
print("课程的平均成绩是: ")
score = student_xy[1:]
sum = 0
for item in score:
sum = sum+int(item[2])
average = sum/len(score)
print(average)
print("按照成绩排名是: ")
score = sorted(score, key=(lambda item: int(item[2])), reverse=True)
print(score)
with open('student123.csv', 'w', encoding='utf-8')as data:
data.write(','.join(student_xy[0])+'\n')
for s in score:
data.write(','.join(s)+'\n')
print("排序后的新文件内容是: ")
with open('student123.csv', 'r', encoding='utf-8')as data:
for line in data:
print(line.strip())
知识点:
- with 语句:使用 with 语句可以不用关闭
- 文件目录方法
5.5 应用实例
问题描述:现有两个文件:一个是保存星座及其时间信息的文本文件,另一个是保存若干人姓名及其生日的“生日.csv”文件,现在要求将“生日.csv”文件中所有人的姓名、生日和星座写入文件“生日星座.csv”,同时将各个星座的人数统计出来,保存到文件“星座统计.txt”中。4 个文件的内容格式如图 5-1 所示。
import csv
def readtxt(filename):
with open(filename, "r")as f:
ls = []
for line in f:
s = line.strip("\n").split(",")
ls.append(s)
xing_all = []
for row in ls:
xing_one = []
if len(row[2]) == 3:
yue1 = row[2][0]
ri1 = row[2][1:3]
else:
yue1 = row[2][0:2]
ri1 = row[2][2:4]
if len(row[3]) == 3:
yue2 = row[3][0]
ri2 = row[3][1:3]
else:
yue2 = row[3][0:2]
ri2 = row[3][2:4]
xing_one.append(row[1])
xing_one.append(int(yue1))
xing_one.append(int(ri1))
xing_one.append(int(yue2))
xing_one.append(int(ri2))
xing_all.append(xing_one)
return xing_all
def readcsv(filename, xing):
with open(filename, "r") as f:
f.readline()
sr = f.readlines()
people = []
for item in sr:
person = []
per = item.strip("\n").split("\t")
date = per[1].split("-")
person.append(per[0])
person.append(date[1]+"月"+date[2]+"日")
for line in xing:
if (int(date[1]) == line[1] and int(date[2]) >= line[2]) or (int(date[1]) == line[3] and int(date[2]) <= line[4]):
per.append(line[0])
break
people.append(per)
return people
def writecsv(filename, people):
with open(filename, "w", newline="")as f:
w = csv.writer(f)
w.writerow(["姓名", "生日", "星座"])
w.writerows(people)
def Stats(people):
dict_num = {}
for line in people:
dict_num[line[2]] = dict_num.get(line[2], 0)+1
return dict_num
def writetxt(filename):
with open(filename, "w")as f:
f.write("星座 人数"+"\n")
f.write("-------------"+"\n")
for key, value in dict_num.items():
f.write(key+" "+str(value)+"\n")
if __name__ == '__main__':
list_xing = readtxt("星座.txt")
list_people = readcsv("生日.csv", list_xing)
writecsv("生日星座.csv", list_people)
dict_num = Stats(list_people)
writetxt("星座统计.txt")