本帖最后由 lxping 于 2022-12-4 20:23 编辑
将代码文件和films.txt放在同一个文件夹里面,运行就可以了def loadFilms():
films = []
i = 0
with open("films.txt") as f:
print(f.read()) #打印films.txt的文件内容
f.seek(0) #指针回到文件初始位置
for each in f.readlines():
i += 1
filmname = each.split(",")[1]
filmmark = float(each.split(",")[2])
filmlist = [i, filmname, filmmark]
films.append(filmlist) #读取films.txt每一行后,按照格式添加到films列表中
return films
def printFilms(films):
print(films)
def addFilms(films):
for i in films:
i[0] += 1 #增加的film是放在最前面的,所以已在列表中的film的序号既rank要调整
filmrank = 1
filmname = input("Please input film name:")
filmmark = float(input("Please input film mark:"))
films.insert(0, [filmrank, filmname, filmmark]) #在列表第一个位置插入新增信息
return films
def saveFilms(films):
with open("newfilms.txt", "w+") as n: #创建新文件
for i in films:
n.writelines(str(i[0]) + "," + i[1] + "," + str(i[2])+ "\n") #每次读取一行,写入一行
if __name__ == "__main__":
films = loadFilms()
films = addFilms(films)
saveFilms(films)
printFilms(films)
= RESTART: C:/Users/Administrator/Desktop/python/homework/once a week/newfilms.py
1,The Shawshank Redemption,9.3
2,The Godfather,9.2
3,The Dark Knight,9.0
Please input film name:Farewell My Concubine
Please input film mark:9.6
[[1, 'Farewell My Concubine', 9.6], [2, 'The Shawshank Redemption', 9.3], [3, 'The Godfather', 9.2], [4, 'The Dark Knight', 9.0]]
|