验证文件上的数据

时间:2019-03-20 16:03:19

标签: python file python-3.7

我正在努力简化工作,并为相同的错误写下错误和解决方案。该程序本身在添加新错误时工作正常,但随后我添加了一个函数来验证文件中是否存在错误,然后对其进行处理(尚未添加)。

该功能不起作用,我也不知道为什么。我尝试调试它,但仍然找不到错误,也许是概念错误?

无论如何,这是我的全部代码。

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()

为澄清起见,程序执行良好,它不返回错误代码。我的意思是,它只是无法执行我打算的方式,它应该验证是否已存在某些错误号。

预先感谢:)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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文件,此代码段才能正常工作。

希望这有所帮助。如果您还有其他问题,请在评论中打我!

参考文献: