почему он говорит «действие не может быть завершено, потому что файл открыт в python“?

#python #windows

#питон #Windows

Вопрос:

 def main_loop():
    global errname, errtime, error_detail, conclusion
    error_detail = ""
    facts_all = {}
    facts = []
    buffer = 0
    current_time = datetime.now()

    while os.path.exists("C:Winusr"):
        print(paths["wintrace"])
        try:
            start_point = 0
            old_size = os.path.getsize(paths["wintrace"])
            while os.path.getsize(paths["wintrace"])>= old_size:
                #fo = open(paths["wintrace"], "rb")
                #fo.seek(start_point,1)
                shutil.copyfile(paths["wintrace"], "C:Winusrwintrace1.log")
                fo = open("C:Winusrwintrace1.log", "rb")
                fo.seek(start_point, 1)
                errtime = datetime(1900, 1, 1)
                old_size = os.path.getsize(paths["wintrace"])
                #start from here
                for line in fo.readlines():
                    line = str(line.decode('ISO-8859-1'))
                    print(line)
                    if fnmatch.fnmatch(line, "*START DUMP LOG BUFFER*"):
                        buffer = 1
                    if fnmatch.fnmatch(line, "*END DUMP LOG BUFFER*"):
                        buffer = 0
                    if buffer == 1:
                        continue

                    facts_all = collect_facts(line,facts_all,key_string,key_value_dic)
                    for pattern in error_detect:
                        if fnmatch.fnmatch(line, pattern):
                            try:
                                err_type = df[df["Error Detect Keyword"] == pattern]["Err Type"].to_string(index=False).lstrip()
                                errname = df[df["Err Type"] == err_type]["Error Name"].tolist()[0].lstrip()

                                errtime = datetime.strptime(
                                datetime.fromtimestamp(os.path.getmtime(paths["wintrace"])).strftime("%Y-%m-%d")   " "   line[:8], "%Y-%m-%d %H:%M:%S") #"%d-%b-%Y %H:%M:%S"
                                #errtime = datetime.fromtimestamp(os.path.getmtime(paths["wintrace"])).strftime("%Y-%m-%d")   " "   line[:8]
                                #errtime = errtime.strftime('%Y-%m-%d %H:%M:%S')
                                product = re.findall(r"[/](. ?)[.]", paths["cur"])
                                product = product[0].split("/")[-1]
                                tester = tester_name(paths["cur"])
                                if len(facts_all) != 0:
                                    facts.append(errname)
                                    #idex = 9999
                                    for fact, line in facts_all.items():
                                        if fact in dic1[errname]:
                                            error_detail = error_detail   line   'n'
                                            facts.append(fact)
                                    print("err_detail1", error_detail)
                                    if len(facts) != 1:
                                        facts = list(set(facts))
                                        conclusion = inference_engine(facts)
                                        print("errtime", errtime)
                                        print("current_time", current_time)
                                        if conclusion != "cannot find solution for this error" and errtime > current_time:
                                            solutions = sop2(errlist, errname, conclusion)
                                            row = recording(tester, product, errname, errtime, error_detail, conclusion)
                                            print("gg pop out GUI!!!")
                                            #send_email(errname, errtime, tester, error_detail)
                                            GUI(errname, errtime, error_detail, conclusion, solutions, row)
                                            current_time = datetime.now()                                 
                                            workbook = xlrd.open_workbook(r"G:expert system dataMachine Database.xls")
                                            workbook1 = copy(workbook)
                                            ws1 = workbook1.get_sheet(0)
                                            style = xlwt.XFStyle()
                                            style.num_format_str = 'yyyy-mm-dd hh:mm:ss'
                                            ws1.write(row, 8, current_time, style)
                                            workbook1.save(r"G:expert system dataMachine Database.xls")
                                            error_detail = ""
                                            facts_all = {}
                                            facts = []
                                    error_detail = ""
                                    facts_all = {}
                                    facts = []
                            except:
                                continue

                start_point = fo.tell()
                fo.close()
        except:
            continue
    else:
        main_loop()
 

пути [«wintrace»] — это «»C:WinusrWintrace.log «, я не хочу, чтобы он был открыт, потому что иногда нужно изменить его имя или удалить, я копирую этот файл и открываю скопированный, но он по-прежнему показывает, что он открыт, можете ли вы помочь мне проверить, где он открыт? кроме того, я использую «filepath = tkinter.filedialog.askopenfilename()», но не думаю, что это откроет файл wintrace.скриншот ошибки

Комментарии:

1. serverfault.com/questions/1966/…

2. Сделайте себе одолжение и используйте with open(...) as f для открытия файла, чтобы убедиться, что он всегда закрыт. Кроме того, сделайте код в этом контексте как можно меньше, чтобы закрыть его как можно скорее.

3. преобразуйте все ваши варианты использования open в use with open . Возможно, вы оставляете файлы открытыми из предыдущих запусков или других программ, особенно если это вызывает исключение. С вызовет другой уровень отступов, поэтому подумайте о том, чтобы разбить ваш код на несколько функций, чтобы его было легче читать.

4. Но я никогда не открываю исходный файл wintrace, я просто справляюсь с ним и открываю скопированный, почему он говорит, что исходный файл открыт, извините, я не понимаю, где я открываю этот файл

5. Я использую монитор ресурсов для проверки, показывает, что исходный файл не находится в процессе обработки, но когда я хочу переименовать его, он все равно отображается открытым в python…