python - 第一次循环后找不到文件或目录
问题描述
我正在尝试创建一个 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()
解决方案
推荐阅读
- wordpress - 删除特定页面的 Jetpack 的 Open Graph 元标记
- c# - 在 DataGridView 中使用嵌套列表作为数据源的列表
- sql - Column' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中
- erlang - elixir/erlang 中的 des-ecb 加密
- visual-studio-code - 在 Visual stuido 行中保存 html 文件时搞砸了
- javascript - 没有 async/await 就不会保存缓存中的更改
- hashcode - 为什么两个具有相似标签的 NodeList 不相等?
- blazor - 更新 Visual Studio 2019 预览后出错
- android - 即使在 postValue() Kotlin 之后 MutableLiveData ArrayList 也是空的
- scala - 在 VScode 中设置 Scala(metals) 时出现问题