(a)将2022年的全年日历逐月显示并存到year2022.txt文件中。 (b)用自定义的getlines函数实现从year.txt文件中提取指定几行的数据,在行首添加行号后,存到lines.txt文件中。 (c)读lines.txt文件内容,并显示出来。
(a)将2022年的全年日历逐月显示并存到year2022.txt文件中。
import calendar
year2022 = open("D:/Desktop/year2022.txt","r+") #开文件,文件是预建的,名字和路径当然是得用自己的
month = [1,2,3,4,5,6,7,8,9,10,11,12] #我承认是我啰嗦了
for i in month:
calendar_2022 = calendar.month(2022,i) #这里不写i这个参数的话就是直接输出年,可笑我还来了个i
print(calendar_2022)
year2022.write(calendar_2022) #写进去就好了
year2022.close() #用完就关好习惯
(b)用自定义的getlines函数实现从year.txt文件中提取指定几行的数据,在 行首 添加行号后,存到lines.txt文件中。
def getlines():
save = []
year2022 = open("D:/Desktop/year2022.txt","r+")
a = int(input("请选择要取的行数:"))
b = int(input("请选择要取的首行:"))
for i in range(1,b):
year2022.readline() #把行都读出来再说
for j in range(0,a):
save.append(str(b+j) + " "+ year2022.readline()) #读出来之后列表追加,便于生成的数据是一行一行的,顺便加上编号,这个地方我并不很清楚是要我从头编还是按照源文件编(我给出的是后者)
lines = open("D:/Desktop/lines.txt","r+")
lines.writelines(save) #把列表数据存入文件
lines.close()
year2022.close() #关文件好习惯,俩都得关上
getlines() #使用函数
(c)读lines.txt文件内容,并显示出来。
lines = open("D:/Desktop/lines.txt","r")
print(lines.read())
lines.close() #没啥好解释的,读个文件然后输出出来
这样上传一下云端,顺便分享一波,还望指教。