从.txt文件打开字典添加/更新新的dict项目并将更新的dict写入.txt文件

时间:2017-10-22 14:28:02

标签: python-3.x

我试图从.txt文件中打开一个字典,添加/更新新的dict项目并将更新的dict写入.txt文件

当我运行程序并给出日期和时间时,我收到此错误:

  

-ValueError:字典更新序列元素#0的长度为1; 2是必需的。

我的代码:

old_dates_hours = {}
dates_hours = {}

def date():
    date = input('\nEnter a date: ')
    while True:
        try:
            hours = float(input('Enter hours: '))
        except ValueError:
            print('That was not a number!')
            continue
        else:
            break
    dates_hours[date.capitalize()] = hours
    answer = ask_yes_no("\nWant to enter more dates?, Enter 'y' of 'n': ")

    return dates_hours

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in ('y', 'n'):
        response = input(question).lower()
        if response == 'y':
            date()
        else:
            print('\nYou dont have more hours to fill in ')

    return response


def open_and_read_file():
    hours_file = open('HOURS.txt', 'r+')
    old_dates_hours = hours_file.readline()
    hours_file.close()

    return old_dates_hours


def write_to_file():
    hours_file = open('HOURS.txt', 'w')
    hours_file.write(str(dates_hours))
    hours_file.close()


dates_hours = date()
print('\nNew entered hours: ', dates_hours)
old_dates_hours = open_and_read_file()
print('\nOld hours: ', old_dates_hours)
print('\nThis are the recently given hours: ', dates_hours)
dates_hours.update(old_dates_hours)
print('This are the total saved hours: ', dates_hours)
write_ = write_to_file()

我测试了" dates_hours.update(old_dates_hours)"函数代码如下: 这对我有用,但我无法在上面的代码中使用它。

old_dates_hours = {'Za': 4, 'Zo': 6}
dates_hours = {'Ma': 13, 'Di': 9, 'Wo': 9, 'Vr': 5}

dates_hours.update(old_dates_hours)
print(dates_hours)

def write_to_file():
    uren_file = open('HOURS3.txt', 'w')
    uren_file.write(str(dates_hours))
    uren_file.close()

write_ = write_to_file()

1 个答案:

答案 0 :(得分:0)

来自here

  

方法update()将字典dict2的键值对添加到   字典。

您的open_and_read_file()函数返回一个列表,而不是字典。因为readlines()返回一个列表。您需要从" HOURS.txt"制作字典,然后尝试更新。

修改

如果你的txt内容类似{'Mo':4, 'Vr':6, 'So':5},你可以使用:

import ast

# rest of the code

def open_and_read_file():
    hours_file = open('HOURS.txt', 'r+')
    old_dates_hours = ast.literal_eval(hours_file.read())
    hours_file.close()

    return old_dates_hours