简体   繁体   中英

how to write dates and list to a text file with Python?

I'm trying to make a program that calculates screen times of various activities as input from user from a date given by the user, and then saves them to a text file. However, I get the following error after the last line of my code:

File "C:\Users\Omistaja\PycharmProjects\tehtava7_3\screen_times.py", line 48, in main
    filename.write("{}: {}".format(pvm, ready_list))
AttributeError: 'str' object has no attribute 'write'

In addition, the text in the file should look like the following examples:

2020-02-27: 0/0/0/0

2020-02-28: 180/0/0/0

2020-02-29: 70/120/0/0

2020-03-01: 75/0/120/0

The code so far:

import datetime


def convert_date_text_to_datetime_object(date_as_text):
    "Returns a datetime.date object converted from string 'date_as_text'."
    date_as_list = date_as_text.split(".")
    day, month, year = [int(part) for part in date_as_list]
    return datetime.date(year, month, day)

def main():
    filename = input("Enter the name of the file to be created for your screen time data:\n")
    file = open(filename, 'w')
    date_text = input("Enter the start date in format 'DD.MM.YYYY':\n")
    pvm = convert_date_text_to_datetime_object(date_text)
    print("Enter your screen watching time for each day (in minutes) in the format '[Phone minutes] [PC minutes] [TV minutes] [other minutes]")
    days = 0
    syotteet_lista = []
    syote = input("Enter your screen time on {}:".format(pvm))
    while syote != "":
        syotteet_lista.append(syote)
        pvm = pvm + datetime.timedelta(days = 1)
        days += 1
        syote = input("Enter your screen time on {}:".format(pvm))
    for syote in syotteet_lista:
        uusi_lista = []
        luvut = syote.split(" ")
        for i in luvut:
            uusi_lista.append(i)
        ready_list = '/'.join(uusi_lista)
    filename.write("{}: {}".format(pvm, ready_list))

filename is a string. You need to use file which is the opened file instead.

Or:

with open(filename, 'w') as f:
    f.write("{}: {}".format(pvm, ready_list))

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