|
发表于 2022-12-10 17:29:38
|
显示全部楼层
本楼为最佳答案
本帖最后由 傻眼貓咪 于 2022-12-10 17:31 编辑
(1)
main.py# 打开文件 MyFile.txt,写入数据
nameHandle = open('MyFile.txt', 'w')
nameHandle.write('one\n')
nameHandle.write('two\n')
nameHandle.close()
# 打开文件 MyFile.txt,读取数据
nameHandle = open('MyFile.txt', 'r')
for line in nameHandle:
print(line[:-1])
nameHandle.close()
# 打开文件 MyFile.txt,在文件尾端写入数据
nameHandle = open('MyFile.txt', 'a')
nameHandle.write('three\n')
nameHandle.write('four\n')
nameHandle.close()
# 打开文件 MyFile.txt,读取数据
nameHandle = open('MyFile.txt', 'r')
for line in nameHandle:
print(line[:-1])
nameHandle.close()
结果:
MyFile.txt
(2)
main.py
students = {'a': 89, 'b': 60, 'c': 45, 'd': 90, 'e': 95}
FILE = open('grade.txt', 'w')
for each in students.items():
name, score = each
FILE.write(f"{name} {score}\n")
FILE.close()
# --------------------- 这是分界线 ---------------------
FILE = open('grade.txt', 'r')
for line in FILE:
name, score = line.split()
if int(score) > 80:
print(f"{name} {score}")
FILE.close()
结果:
grade.txt打印结果:
|
|