简体   繁体   中英

Python- replacing date stored in csv file with a string

I have a csv file that stores dates (format 12 june 2019,), i want to replace a date that a user chooses with 0 (basciaclly deleting it) when ever the function is called. The code runs with no errors however when i check the file again the date hasnt been replaced.

from datetime import datetime


def Remove_event():
    date_string = input("Enter date for event (Format: day month, year): ")

    date_object = datetime.strptime(date_string, "%d %B, %Y")  # converts inputted date into date time data type
    date_object = date_object.strftime("%d %B, %Y")  # formats the date
    date_object = date_object.replace(",", "")  # removes comma in the middle
    date_object1 = date_object + ","  # adds comma at the end

    f = open("dates1.csv", "rt")
    data = f.read()
    data = data.replace(date_object1, '0')
    print("yes")
    f.close()


Remove_event()

You need to add the following code at the end to actually write the replacement to the file:

fin = open("dates1.csv", "wt")
fin.write(data)
fin.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM