首页 > 解决方案 > 第一次循环后找不到文件或目录

问题描述

我正在尝试创建一个 python 程序,在输入一定数量的单词后“覆盖”一个列表(我在程序前面创建的)。我说“覆盖”是因为一旦达到我的最大字数,我就会让我的程序删除文件并重新运行程序并重新创建文件。该程序一开始运行良好,但是当第一个循环到来时,我得到一个文件或目录“History.txt”未找到。不知道为什么即使我在程序中创建文件本身

# This creates the file and everything below the first line is formatting to it looks nice
    with open("History.txt", "a") as f:
        for key in keys:
            k = str(key).replace("'", "")
            if k.find("space") > 0:
                f.write('\n')
            elif k.find("Key") == -1:
                f.write(k)
# This defined the number of words in the list
    filename = 'History.txt'
    numWords = 0

    with open(filename, 'r') as file:
        for line in file:
            wordsList = line.split()
            numWords += len(wordsList)

编辑:这是一些可重现的代码。对于最少的代码来说它有点长,但是 on_press 和 write_file 可以忽略,因为它们只是用于 .txt 文件的字格式。您会注意到这一切正常,History.txt 文件被删除。但是引入while循环会导致错误。

from pynput.keyboard import Key, Listener

while True:
    count = 0
    keys = []


    def on_press(key):
        global keys, count

        keys.append(key)
        count += 1

        if count >= 1:  # Starts recording keys after I press any key
            count = 0
            write_file(keys)
            keys = []


    def write_file(keys):  # This function creates spaces between words
        with open("History.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'", "")
                if k.find("space") > 0:
                    f.write('\n')
                elif k.find("Key") == -1:
                    f.write(k)


    def on_release(key):
        filename = 'History.txt'
        num_words = 0

        with open(filename, 'r') as file:
            for line in file:
                words_list = line.split()
                num_words += len(words_list)

        if num_words == 5:
            import os  # I changed this from the earlier remove function but it does the same
            os.remove(filename)

            return False


    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

标签: pythonpython-3.xfilewhile-loop

解决方案


推荐阅读