简体   繁体   English

逐行读取文件并仅在完成后打印

[英]read a file line by line and print only after its done

So I am working on doing a "simple" task since like 2h and still can't find the solution, so where is my question : I want to search in a file, line by line, and if no result is found, at the end print something, else call a function. 所以我正在做一个“简单”的任务,因为像2h一样,仍然找不到解决方案,所以我的问题在哪里:我想逐行搜索文件,如果找不到结果,请在结束打印一些东西,否则调用一个函数。

def DeletItemCheckUp():
    import re
    find = True
    itemNumber = input("\n what is the item you want to delet : ")
    fileItem = open('Data_Item', 'r', encoding='Utf-8')
    for line in fileItem:
        sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
        if (sr == None):
            pass
    print("This item don't exist.")
    fileItem.close()
    if (find == True):
        return itemNumber
        DeletItem()

so here is the problem I have got with different try : 1. Print "This item don't exist." 因此,这是我尝试其他方法时遇到的问题:1.打印“此项目不存在”。 for every line that didn't had my itemNumber. 对于没有我的itemNumber的每一行。 2. When there was actually no match found, its would not call DeletItem(). 2.当实际上找不到匹配项时,它不会调用DeletItem()。

objectif of the code : Ask for a item to delet, check in a file if the unique item number exist, if so, call DeletItem() to delet it, else, tell the user that this unique item number don't exist. 代码的对象:要求删除项目,在文件中检查是否存在唯一项目号,如果存在,则调用DeletItem()删除它,否则,告诉用户该唯一项目号不存在。

Few overlooks in there to achieve what you ask. 很少有人可以忽略那里以实现您的要求。 We are going to use a flag (true/false) to know when we found something, and based on that we will decide whether to call the function or print/return the number. 我们将使用一个标志(true / false)来了解何时发现了某些内容,并以此为基础决定是调用函数还是打印/返回数字。

def DeletItemCheckUp():
    import re
    find = False      # initialize to False
    itemNumber = input("\n what is the item you want to delet : ")
    fileItem = open('Data_Item', 'r', encoding='Utf-8')
    for line in fileItem:
        sr = re.search(r'^\b%s\b'%itemNumber,(line.split(';')[0]))
        if (sr == None):
            continue  # do nothing and continue
        else:
            # we found the number, set the flag and break
            find = True
            break  # no need to continue searching
    fileItem.close()
    if (find):
        DeletItem()           # call the function
    else:
        print("This item don't exist.")

1) replace the pass with your print('This item doesn't exist'). 1)将通行证替换为您的印刷品(“此商品不存在”)。 "Pass" means "do nothing." “通过”表示“什么都不做”。

2) Your DeleteItem() is after the return. 2)您的DeleteItem() 返回之后。 Nothing executes after the return because you have returned to the place the function was called from. 返回之后没有任何执行,因为您已经返回到调用该函数的位置。 You want 你要

else:
    DeleteItem()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM