您的位置:首页 > 编程语言 > Python开发

python 实验九 文件与异常

2021-06-05 18:48 1286 查看

1.新建一个文本文件yzy.txt,文件内容如下
慈母手中线,游子身上衣。
临行密密缝,意恐迟迟归。
谁言寸草心,报得三春晖。
编写程序输出该文件的内容,要求使用一次性读入整个文件内容和逐行读取文件内容的两种方式。

file = open('yzy.txt', 'r', encoding='utf-8')
print(file.read())
file.close()

file = open('yzy.txt', 'r', encoding='utf-8')
print(file.readline())
print(file.readline())
print(file.readline())
print(file.readline())
file.close()

输出结果:

慈母手中线,游子身上衣。
临行密密缝,意恐迟迟归。
谁言寸草心,报得三春晖。
慈母手中线,游子身上衣。

临行密密缝,意恐迟迟归。

谁言寸草心,报得三春晖。

2.计算运动会某个参赛者选手得分。假设共有10个裁判,每个裁判给该选手打分(分值0~10之间)后,去掉一个最高分和一个最低分之后的平均分极为该运动员的最后得分。某位选手的得分数据保存在文件中,文件内容如下:
9.37  9.52  9.98   10  9.85  9.73  9.93   9.76  9.81  9.08
各数据之间使用一个空格分隔。请编写程序从文件中读取该选手的成绩并计算最后得分。

file = open('9-2.txt', 'r', encoding='utf-8')
content = file.read()
file.close()

scores = [float(n) for n in content.split()]
print(scores)

maxScore = max(scores)
minScore = min(scores)
scores.remove(maxScore)
scores.remove(minScore)
print(scores)
print(sum(scores) / len(scores))

输出结果:

[9.37, 9.52, 9.98, 10.0, 9.85, 9.73, 9.93, 9.76, 9.81, 9.08]
[9.37, 9.52, 9.98, 9.85, 9.73, 9.93, 9.76, 9.81]
9.74375

3.文件a.txt中每一行内容分别为购买的商品名称,价格,数量,求出所购商品花费的总费用。
apple 10 3
focus 100000 1
surface 8000 2
thinkpad 7000 3
chicken 10 3

cost = []
with open('a.txt', 'r') as file:
for row in file.readlines():
ls = row.split(' ')
cost.append(int(ls[1]) * int(ls[2]))
print(sum(cost))

输出结果:

137060

4.新建一个文本文件score.csv,用来保存10名考生3门课程成绩,内容如下:
考号,程序设计,细胞生物,生理学
10153450101,72,96,88
10153450102,68,88,73
10153450103,63,63,66
10153450104,95,64,65
10153450105,89,88,57
10153450106,77,87,77
10153450107,67,64,97
10153450108,44,99,64
10153450109,82,73,75
10153450110,79,78,85
以上各数据均使用英文逗号分隔。请编写程序读取文件内容,统计每门课程的平均成绩,最高分和最低分。

# 统计score.CSV文件中每门课程的平均成绩、最高分和最低分。

# 方法一
with open('score.csv', "r", encoding='utf-8') as file:
LS = list(file)
del LS[0]  # 去掉标题行

ls1, ls2, ls3 = [], [], []
for s in LS:
x = s[:-1].split(',')  # 因为最后一个字符是回车符\n,s[:-1]相当于去掉了最后的回车符
ls1.append(int(x[1]))
ls2.append(int(x[2]))
ls3.append(int(x[3]))

print('程序设计课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls1) / len(ls1), max(ls1), min(ls1)))
print('细胞生物课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls2) / len(ls2), max(ls2), min(ls2)))
print('生理学课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls3) / len(ls3), max(ls3), min(ls3)))

# 方法二,使用内置csv库和字典读法
import csv

ls1, ls2, ls3 = [], [], []
with open('score.csv', "r", encoding='utf-8') as file:  # 用with打开文件,可以不用去特意关闭file了
reader = csv.DictReader(file)
for row in reader:
# print(row)
ls1.append(int(row["程序设计"]))
ls2.append(int(row["细胞生物"]))
ls3.append(int(row["生理学"]))

print('程序设计课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls1) / len(ls1), max(ls1), min(ls1)))
print('细胞生物课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls2) / len(ls2), max(ls2), min(ls2)))
print('生理学课程平均成绩:{:.2f},最高分{},最低分{}'.format(sum(ls3) / len(ls3), max(ls3), min(ls3)))

输出结果:

程序设计课程平均成绩:73.60,最高分95,最低分44
细胞生物课程平均成绩:80.00,最高分99,最低分63
生理学课程平均成绩:74.70,最高分97,最低分57
程序设计课程平均成绩:73.60,最高分95,最低分44
细胞生物课程平均成绩:80.00,最高分99,最低分63
生理学课程平均成绩:74.70,最高分97,最低分57

5.新建一个文本文件zen.txt,文件内容为"python之禅"的部分内容,具体如下:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
编写程序统计该文件内容的行数及单词个数。

with open('zen.txt', "r", encoding='utf-8') as file:
content = file.readlines()

words = [len(row[:-1].split()) for row in content]

print(f'行数:{len(content)}')
print(f'单词的个数:{sum(words)}')

输出结果:

行数:4
单词的个数:20

6.编写程序随机产生100个两位数正整数,并将这100个数写入文件number.txt中,要求每行10个整数,整数之间用一个空格分隔。

import random

data = [random.randint(10, 100) for i in range(100)]

with open('number.txt', "w", encoding='utf-8') as file:
k = 0
for d in data:
file.write(str(d) + ' ')
k = k + 1
if k % 10 == 0:
file.write('\n')

输出样例:

52 82 93 48 89 17 42 52 41 63
79 21 100 16 76 91 28 37 94 61
46 89 84 36 84 76 62 76 33 38
27 94 59 95 10 100 51 26 69 63
82 15 15 50 78 27 19 37 73 20
14 63 55 45 83 51 50 83 58 62
39 49 10 73 95 27 54 36 63 55
93 63 35 16 43 10 22 69 14 63
24 72 55 59 52 37 24 98 45 53
40 15 21 100 79 86 86 61 52 21

7.编写程序读取题1中内容并显示在一行同时将这一行写入另一个文本文件yzy2.txt中。

with open('yzy.txt', "r", encoding='utf-8') as file:
content = file.read()
s = content.replace('\n', '')

print(s)

with open('yzy2.txt', "w", encoding='utf-8') as file:
file.write(s)

输出结果:

慈母手中线,游子身上衣。临行密密缝,意恐迟迟归。谁言寸草心,报得三春晖。

8.某文件的内容为"Hello world",编写程序将该文件的"world"替换为其他的内容,如"python"。

# 将文件内容“Hello world”中的“world”替换为“Python”。

with open('9-8.txt', "r", encoding='utf-8') as file:
content = file.read()
s = content.replace('world', 'Python')

with open('9-8.txt', "w", encoding='utf-8') as file:
file.write(s)

输出结果:

Hello Python

9.新建一个文本文件yzy3.txt,编写程序将如下两行内容写入该文件中:
游子吟:
唐代:孟郊
接着读取题1的文本内容,追加到文件yzy3.txt末尾,最后文件yzy3.txt的内容如下:

file = open('yzy.txt', 'r', encoding='utf-8')
content = file.read()
file.close()

file = open('yzy3.txt', 'a', encoding='utf-8')
file.write('游子吟\n')
file.write('唐代:孟郊\n')
file.write(content)
file.close()

输出结果:

游子吟
唐代:孟郊
慈母手中线,游子身上衣。
临行密密缝,意恐迟迟归。
谁言寸草心,报得三春晖。

10.读取任意一个python源代码文件(py.文件),在源代码每行的左边加上行号,且行号与代码间保留一个空格,最后将含有行号的代码保存至一个新的文件内。

with open('实验9-9.py', "r", encoding='utf-8') as file:
lines = file.readlines()
ls = [str(i + 1) + ' ' + line for i, line in enumerate(lines)]
new_content = ''.join(ls)
print(new_content)

with open('实验9-9_带行号.txt', "w", encoding='utf-8') as file:    #新建一个文件实验9-9_带行号.txt
file.write(new_content)

输出结果:

1 file = open(‘yzy.txt’, ‘r’, encoding=‘utf-8’)
2 content = file.read()
3 file.close()
4
5 file = open(‘yzy3.txt’, ‘a’, encoding=‘utf-8’)
6 file.write(‘游子吟\n’)
7 file.write(‘唐代:孟郊\n’)
8 file.write(content)
9 file.close()

11.编写程序统计题5中zen.txt文件内单词的词频,并将统计的结果保存至一个新的文件内。词频即相同单词出现的次数,如zen.txt文件中better词频为4,Simple的词频为1。

with open('zen.txt', "r", encoding='utf-8') as file:
content = file.read().lower().replace('\n', '').replace('.', ' ')

words = content.split()
dic_fq = {}
for word in words:
dic_fq[word] = dic_fq.get(word, 0) + 1

for fq in dic_fq.items():
print(f'{fq[0]}:{fq[1]}')

# 另一种方法:使用collections库中的Counter,更简洁
from collections import Counter

print('-----------')
result = Counter(words)
for r in result.items():
print(f'{r[0]}:{r[1]}')

输出结果:

beautiful:1
is:4
better:4
than:4
ugly:1
explicit:1
implicit:1
simple:1
complex:2
complicated:1

12.某文件data.txt中存放若干个整数,各整数之间使用英文逗号分隔,编写程序读取文件中的所有整数,将其升序排列后保存至一个新的文件内。

with open('9-12.txt', "r", encoding='utf-8') as file:
content = file.read()

data = [int(d) for d in content.split(',')]
data.sort()

new_content = ','.join([str(d) for d in data])
print(new_content)

with open('9-12_sort.txt', "w", encoding='utf-8') as file:
file.write(new_content)

输出样例:

12,34,56,78

13.文件website.txt存放的是网站名称,内容如下:
Python官网,www.python.org
Python第三方库,pypi.org
清华大学开源软件镜像站,mirrors.tuna.tsinghua.edu.cn
Anaconda,www.anaconda.com
PyCharm,www.jetbrains.com/pycharm
另一个文件url.txt存放的是网站的网址,内容如下:

with open('website.txt ', "r", encoding='utf-8') as file:
website = file.read().splitlines()  # .split('\n')
with open('url.txt ', "r", encoding='utf-8') as file:
url = file.read().splitlines()  # .split('\n')
print(website)
print(url)

comb = list(zip(website, url))
print(comb)

ls = [d[0] + ',' + d[1] for d in comb]
content = '\n'.join(ls)
print(content)

with open('website_url.txt', "w", encoding='utf-8') as file:
file.write(content)

输出结果:

[‘Python官网’, ‘Python第三方库’, ‘清华大学开源软件镜像站’, ‘Anaconda’, ‘PyCharm’]
[‘www.python.org’, ‘pypi.org’, ‘mirrors.tuna.tsinghua.edu.cn’, ‘www.anaconda.com’, ‘www.jetbrains.com/pycharm’]
[(‘Python官网’, ‘www.python.org’), (‘Python第三方库’, ‘pypi.org’), (‘清华大学开源软件镜像站’, ‘mirrors.tuna.tsinghua.edu.cn’), (‘Anaconda’, ‘www.anaconda.com’), (‘PyCharm’, ‘www.jetbrains.com/pycharm’)]
Python官网,www.python.org
Python第三方库,pypi.org
清华大学开源软件镜像站,mirrors.tuna.tsinghua.edu.cn
Anaconda,www.anaconda.com
PyCharm,www.jetbrains.com/pycharm

14.文件score.txt保存了学生的平时成绩和期末成绩,内容如下:
学号,平时成绩,期末成绩
9999180101,77,88
9999180102,91,85
9999180103,87,96
9999180104,70,68
9999180105,86,72
编写程序读取所有成绩,计算总评成绩(四舍五入到整数),其中总评成绩=平时成绩40%+期末成绩60%。最后按总评成绩降序排列后保存至一个新的文件内,文件内容应该如下:

import csv

with open('score.txt ', "r", encoding='utf-8') as file:
data = list(csv.reader(file))[1:]  # 去除标题行
print(data)

for d in data:
d.append(str(round(int(d[1]) * 0.4 + int(d[2]) * 0.6)))
print(data)

data.sort(key=lambda x: x[3], reverse=True)
data.insert(0, ['学号', '平时成绩', '期末成绩', '总评成绩'])
# print(data)

with open('score_total.txt ', "w", encoding='utf-8', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)

# 另一种方法,使用DictReader和DictWriter,可读性较好
with open('score.txt ', "r", encoding='utf-8') as file:
data = list(csv.DictReader(file))  # DictReader并不包含第一行标题行

for d in data:
# print(d)
d['总评成绩'] = str(round(int(d['平时成绩']) * 0.4 + int(d['期末成绩']) * 0.6))
print(d)
data.sort(key=lambda d: d['总评成绩'], reverse=True)
# print(data)
# for d in data:
#     print(d)
fieldnames = ['学号', '平时成绩', '期末成绩', '总评成绩']
with open('score_total.txt ', "w", encoding='utf-8', newline='') as file:
writer = csv.DictWriter(file, fieldnames)
writer.writeheader()
writer.writerows(data)

输出结果:

学号,平时成绩,期末成绩,总评成绩
9999180103,87,96,92
9999180102,91,85,87
9999180101,77,88,84
9999180105,86,72,78
9999180104,70,68,69

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: