【问题标题】:Removing a random choice from a text file从文本文件中删除随机选择
【发布时间】:2020-03-24 01:39:51
【问题描述】:

所以我正在为我的女朋友构建一个日期生成器,但一旦选择了它,我似乎无法从样本池中删除日期。 dateChoice() 会实际选择有效的日期,但dateRemover() 似乎不起作用。我已经阅读了一堆 .txt 写作和阅读,但我似乎无法让它发挥作用。谢谢!

import random

#Imports date list
dateList = open("file", 'r+')
dates = dateList.readlines()
line = "-----------------------------------------"
choice = ""
date = ""

#Selects a Date
def dateChoice():
    date = random.choice(dates)
    print("Your date is: {}".format(date)

#Removes date from list
def dateRemover():
    choice = input("Would you like to remove the date from the list?")
    if str.upper(choice) in ["Y", "YES"]:
        print(line)
        dateList.seek(0)
        for i in dates:
            if i != date:
                dateList.write(i)
        dateList.truncate()
        print("All is done")
    elif str.upper(choice) in ["N", "NO"]:
        print(line)
        print("Okay. your date is still in the system!")
    else:
        print(line)
        print("Please answer with either Yes or No")
        dateRemover()


#Start of program
def start():
    dateChoice()
    dateRemover()

#Runs programs
start()

【问题讨论】:

  • 您在“dateChoice”中创建了一个局部变量“date”,它会影响全局变量并在函数退出时丢失。在函数开始时将其声明为“全局”。

标签: python python-3.x list for-loop text


【解决方案1】:

Michael Butscher 的评论是正确的,像这样:

#Selects a Date
def dateChoice():
    global date
    date = random.choice(dates)
    print("Your date is: {}".format(date))

另外,您在打印件上缺少右括号

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2012-08-15
    相关资源
    最近更新 更多