验证文件上的数据

问题描述 投票:0回答:2

我正努力让我的工作变得更轻松,并为同样的错误写下错误和解决方案。程序本身在添加新错误时工作正常,但随后我添加了一个函数来验证文件中是否存在错误,然后对其执行某些操作(尚未添加)。

该功能不起作用,我不知道为什么。我试图调试它,但仍然无法找到错误,可能是一个概念错误?

无论如何,这是我的整个代码。

import sys
import os

err = {}
PATH = 'C:/users/userdefault/desktop/errordb.txt'

#def open_file():  #Not yet used
    #file_read = open(PATH, 'r')
    #return file_read

def verify_error(error_number, loglist): #Verify if error exists in file
    for error in loglist:
        if error_number in loglist:
            return True


def dict_error(error_number, solution): #Puts input errors in dict
    err = {error_number: solution}
    return err

def verify_file(): #Verify if file exists. Return True if it does
    archive = os.path.isfile(PATH)
    return archive

def new_error():
    file = open(PATH, 'r') #Opens file in read mode
    loglist = file.readlines()
    file.close()
    found = False
    error_number = input("Error number: ")
    if verify_error(error_number, loglist) == True:
        found = True
        # Add new solution, or another solution.
        pass
    solution = str(input("Solution: "))
    file = open(PATH, 'a')
    error = dict_error(error_number, solution)
    #Writes dict on file
    file.write(str(error))
    file.write("\n")
    file.close()

def main():
    verify = verify_file() #Verify if file exists
    if verify == True:
        new = str.lower(input("New job Y/N: "))
        if new == 'n':
            sys.exit()
        while new == 'y':
            new_error()
            new = str.lower(input("New job Y/N: "))
        else:
            sys.exit()
    else:
        file = open(PATH, "x")
        file.close()
        main()

main()

为了澄清,程序执行正常,它不返回错误代码。它只是不会执行我的意图,我的意思是,它应该验证是否已经存在某些错误号。

提前致谢 :)

python file python-3.7
2个回答
0
投票

我相信你遇到的问题是你实际上并没有在文件中创建dictionary object并修改它,而是每次添加错误时创建其他词典,然后使用.readlines()将它们作为字符串列表读回来方法。

更简单的方法是创建一个dictionary(如果不存在)并向其追加错误。我对你的代码做了一些修改应该有所帮助。

import sys
import os
import json  # Import in json and use is as the format to store out data in

err = {}
PATH = 'C:/users/userdefault/desktop/errordb.txt'

# You can achieve this by using a context manager
#def open_file():  #Not yet used
    #file_read = open(PATH, 'r')
    #return file_read

def verify_error(error_number, loglist): #Verify if error exists in file
    # Notice how we're looping over keys of your dictionary to check if
    # an error already exists.
    # To access values use loglist[k]
    for k in loglist.keys():
        if error_number == k:
            return True
    return False

def dict_error(loglist, error_number, solution): #Puts input errors in dict
    # Instead of returning a new dictionary, return the existing one
    # with the new error appended to it 
    loglist[error_number] = solution
    return loglist

def verify_file(): #Verify if file exists. Return True if it does
    archive = os.path.isfile(PATH)
    return archive

def new_error():

    # Let's move all the variables to the top, makes it easier to read the function
    # Changed made:
    # 1. Changed the way we open and read files, now using a context manager (aka with open() as f:
    # 2. Added a json parser to store in and read from file in a json format. If data doesn't exist (new file?) create a new dictionary object instead
    # 3. Added an exception to signify that an error has been found in the database (this can be removed to add additional logic if you'd like to do more stuff to the error, etc)
    # 4. Changed the way we write to file, instead of appending a new line we now override the contents with a new updated dictionary that has been serialized into a json format
    found = False
    loglist = None

    # Open file as read-only using a context manager, now we don't have to worry about closing it manually
    with open(PATH, 'r') as f:
        # Lets read the file and run it through a json parser to get a python dictionary
        try:
            loglist = json.loads(f.read())
        except json.decoder.JSONDecodeError:
            loglist = {}

    error_number = input("Error number: ")
    if verify_error(error_number, loglist) is True:
        found = True
        raise Exception('Error exists in the database')  # Raise exception if you want to stop loop execution
        # Add new solution, or another solution.

    solution = str(input("Solution: "))
    # This time open in write only and replace the dictionary
    with open(PATH, 'w') as f:
        loglist = dict_error(loglist, error_number, solution)
        # Writes dict on file in json format
        f.write(json.dumps(loglist))

def main():
    verify = verify_file() #Verify if file exists
    if verify == True:
        new = str.lower(input("New job Y/N: "))
        if new == 'n':
            sys.exit()
        while new == 'y':
            new_error()
            new = str.lower(input("New job Y/N: "))
        else:
            sys.exit()
    else:
        with open(PATH, "x") as f:
            pass
        main()

main()

请注意,您必须为此代码段创建新的errordb文件才能生效。

希望这有所帮助。如果您有任何其他问题,请在评论中告诉我!

参考文献:


0
投票

我认为您的代码可能存在一些问题,但我注意到的第一件事是您将错误号码和解决方案保存为errorsdb.txt中的字典,当您阅读它们时,您正在将它们作为字符串列表:

这条线:

loglist = file.readlines()

new_error中返回一个字符串列表。这意味着verify_error将永远返回False

所以你有几个选择:

  1. 您可以将verify_error修改为以下内容:
def verify_error(error_number, loglist): #Verify if error exists in file
    for error in loglist:
        if error_number in error:
            return True
  1. 虽然,我认为更好的解决方案是将errorsdb.txt加载为JSON文件然后你将有一本字典。这看起来像是这样的:
import json

errordb = {}
with open(PATH) as handle:
    errordb = json.load(handle)

所以这里是我要做的全套改变:

import json

def verify_error(error_number, loglist): #Verify if error exists in file
    for error in loglist:
        if error_number in error:
            return True

def new_error():
    errordb = list()
    exitsting = list()
    with open(PATH) as handle:
        existing = json.load(handle)

    errordb += existing

    error_number = input("Error number: ")
    if verify_error(error_number, errordb) == True:
        # Add new solution, or another solution.
        print("I might do something here.")
    else:
        solution = str(input("Solution: "))
        errordb.append({error_number, solution})

    #Writes dict on file
    with open(PATH, "w") as handle:
        json.dump(errordb, handle)

© www.soinside.com 2019 - 2024. All rights reserved.