本文最后更新于 527 天前,其中的信息可能已经有所发展或是发生改变。
文章目录[隐藏]
第1关:读取文件
任务描述
本关任务:编写程序,输入文件名,读取文件,按照说明进行显示。 文件格式为: 学号,姓名,成绩 输出格式为:
相关知识
为了完成本关任务,你需要掌握:1.如何读取文件。
编程要求
根据提示,在右侧编辑器补充代码。文件名称为:
测试说明
平台会对你编写的代码进行测试:
测试输入:student.txt
; 预期输出: [('\ufeff2022001', 'zhang', '90'), ('2022002', 'wang', '85'), ('2022003', 'li', '75'), ('2022004', 'zhao', '60'), ('2022005', 'zhou', '75'), ('2022006', 'wu', '85')]
import os
fname=input()
filename = os.path.join('/data/workspace/myshixun/my_file/',fname)
file = open(filename,'r')
listA = []
for line in file:
line = line.replace('\n','')
listB = line.split(',')
listA.append(tuple(listB))
print(listA)
老师的标答,就是对换行符的处理不一样,以及处理了数字类型转换
一定要注意tuple()
这个转元组的函数啊
import os
fname=input()
filename = os.path.join('/data/workspace/myshixun/my_file/',fname)
file = open(filename,'r')
listA = []
for line in file:
line = line[:-1]
listB = line.split(',')
listB[2] = int(listB[2])
listA.append(tuple(listB))
print(listA)
第2关:复制文件
任务描述
本关任务:编写程序,输入源文件名和目标文件名,将源文件的内容拷贝到目标文件。
相关知识
为了完成本关任务,你需要掌握:1.如何读取文件,2.如何写文件。
编程要求
根据提示,在右侧编辑器补充代码。
测试说明
平台会对你编写的代码进行测试:
测试输入:source.txt,dest.txt
; 预期输出: `print('hello world')
print('be or not be')
print('knowledge is power')
True `
import os
def check(src,dest):
srcfile = open(src)
destfile = open(dest)
for line in srcfile:
destline = destfile.readline()
if line == destline:
continue
else:
return False
return True
s=input()
src,dest = s.split(',')
source = os.path.join('/data/workspace/myshixun/my_file/',src)
dest_file = os.path.join('/data/workspace/myshixun/my_file/',dest)
file_source = open(source,"r")
file_dest = open(dest_file,"w")
for line in file_source:
print(line)
file_dest.write(line)
file_source.close()
file_dest.close()
flag = check(source,dest_file)
print(flag)
第3关:读取文件并分析文件
任务描述
本关任务:编写程序,读取文件,删除程序文件中的单行注释,并显示删除注释后的文件。
相关知识
为了完成本关任务,你需要掌握:1.如何读取文件,2.如何删除注释。
编程要求
根据提示,在右侧编辑器补充代码。
测试说明
平台会对你编写的代码进行测试:
测试输入:helloworld.py
; 预期输出: print('hello world')
import os
s=input()
filename = os.path.join('/data/workspace/myshixun/my_file/',s)
file = open(filename,"r")
for line in file:
if line[0] == "#":
continue
else:
for i in line:
if i == "#":
print()
break
else:
print(i,end='')
file.close()