我刚开始编程,我试着构建这个生日提醒应用程序,但没有遵循特定的教程,而是试图自己解决它,但我被困住了。
第一个函数将生日添加到.txt文件中,没有问题。但是对于第二个问题,无论我试图从birthday_dict或文件中检索生日数据,这个函数都不会运行。
对于第二个函数,我尝试调整这个https://www.geeksforgeeks.org/birthday-reminder-application-python/,但是它仍然不能工作。
如果有人能帮我,那就太好了。谢谢!
import datetime
from datetime import date, timedelta
birthday_dict = {}
def add_to_log():
name = input("Name: ")
date_str = input("Birthday (day/month) :")
birthday_dict.update({name: date_str})
with open('./venv/birthday_log.txt', mode='a') as birthday_log:
file = birthday_log.write(f'\n {name}:{date_str}')
print ('Birthday added!')
def reminder():
file = open('birthday_log.txt', 'r')
today = date.today()
today.strftime("%d/%m")
flag = 0
for line in file:
if today in file:
line = line.split(':')
flag = 1
print (f'Today is {line[1]}\'s birthday!')发布于 2020-09-03 06:21:34
这个脚本包含了几个错误。我试着一个接一个地给他们讲讲。我给它们编号以供参考。
./venv/birthday_log.txt', and in another place you use birthday_log.txt` (没有子文件夹)。这可以通过将文件名移动到全局变量或函数参数来解决。特别是当您开始编程时,我强烈反对使用全局变量,因此让我们使用函数参数(参见下面的)。
当使用
.strftime(...),您可以正确地做到这一点。但该调用将返回字符串值。它将不会修改现有的date对象。因此,您需要将结果存储在一个新变量中,以便以后可以使用它。in运算符。我们需要在in操作符的两边使用“字符串”。在左边,我们可以使用我们在2中创建的新变量,在右边,我们可以使用line,它表示我们正在循环的当前行。还有一些小窍门:
您可以使用variable
birthday_dict.update({name: date_str})的类型,您也可以简单地编写birthday_dict[name] = date_str小“练习”
全局变量的
birthday_dict。想一想如何使它成为“局部变量”。提示:它非常类似于对文件名所做的更改.import datetime
from datetime import date, timedelta
birthday_dict = {}
def add_to_log(filename):
name = input("Name: ")
date_str = input("Birthday (day/month) :")
birthday_dict.update({name: date_str})
# [1] Using a variable here makes it easier to ensure we only specify the
# filename once
with open(filename, mode='a') as birthday_log:
file = birthday_log.write(f'\n {name}:{date_str}')
print ('Birthday added!')
def reminder(filename):
# [1] Using a variable here makes it easier to ensure we only specify the
# filename once
file = open(filename, 'r')
today = date.today()
# [2] After creating a reference for "today", you need to store the
# "string" conversion in a new variable and use that later
today_str = today.strftime("%d/%m")
flag = 0
for line in file:
# [3] You want to check that the date you need is contained in the
# line, not the file object
if today_str in line:
line = line.split(':')
flag = 1
print (f'Today is {line[1]}\'s birthday!')
add_to_log("birthday_log.txt")
reminder("birthday_log.txt")发布于 2020-09-03 06:02:20
要查看文件中的所有行,您需要从带有.readlines()的变量中运行open(),这将生成如下列表:
file = open("test.txt", "r")
lines = file.readlines() # lines = ['hello','test']lines变量将是一个列表,您可以这样做:
for line in lines:
print(line)另外,您可能希望在第二个函数中编写for today in line。
https://stackoverflow.com/questions/63717583
复制相似问题