验证fi上的数据

2024-04-26 05:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着让我的工作更轻松,写下错误和解决同样错误的方法。程序本身在添加新错误时工作正常,但是我添加了一个函数来验证文件中是否存在错误,然后对其执行一些操作(尚未添加)。你知道吗

这个功能不起作用,我也不知道为什么。我试着调试它,但仍然找不到错误,也许是概念上的错误?你知道吗

不管怎样,这是我的全部代码。你知道吗

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

为了澄清,程序执行良好,它不返回错误代码。它只是不会按我的预期方式执行,我是说,它应该验证某个错误号是否已经存在。你知道吗

提前感谢:)


Tags: pathintruenumbernewinputifdef
2条回答

我认为您遇到的问题是,您实际上并不是在文件中创建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文件,此代码段才能工作。你知道吗

希望这能有所帮助。如果您有任何进一步的问题,请在评论中联系我!你知道吗

参考文献:

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

线路:

loglist = file.readlines()

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

相关问题 更多 >