遇ValueError: I/O operation on closed file,如何用pyautogui输入pytest.txt内容?
问题解决:ValueError: I/O operation on closed file 及文本输入实现
错误原因
你存在两个核心问题:
- 直接将文件对象赋值给了
characters,with代码块执行结束后会自动关闭文件,后续操作这个已关闭的文件对象就会触发ValueError。 - 误用
pyautogui.press():该函数用于模拟单个按键按下,无法直接输入字符串或文本行,输入文本应该用pyautogui.typewrite()。
修正方案
- 在
with块内读取文件实际内容,而非保存文件对象:- 用
text.read()读取全部内容(适合一次性输入) - 用
text.readlines()按行读取(适合逐行输入)
- 用
- 替换
pyautogui.press()为pyautogui.typewrite()实现文本输入 - 简化循环和变量逻辑,删除冗余代码
完整修正代码
方案1:一次性输入文件全部内容
import keyboard import pyautogui # 读取文件全部内容,去除首尾空白 with open("pytest.txt", "r") as text: content = text.read().strip() break_flag = False while True: if break_flag: break # 按下*键开始输入文本 if keyboard.is_pressed('*'): pyautogui.typewrite(content) # 等待再次按*键退出循环(可根据需求删除此段) while not keyboard.is_pressed('*'): pass break_flag = True
方案2:逐行输入文件内容
import keyboard import pyautogui # 按行读取文件,过滤空行并去除每行首尾空白 with open("pytest.txt", "r") as text: lines = [line.strip() for line in text if line.strip()] break_flag = False while True: if break_flag: break if keyboard.is_pressed('*'): for line in lines: pyautogui.typewrite(line) pyautogui.press('enter') # 每行输入完按回车,可根据需求删除 # 中途按*键停止输入 if keyboard.is_pressed('*'): break break_flag = True
补充说明
- 如果需要模拟人工输入的延迟,可给
typewrite()添加interval参数,比如pyautogui.typewrite(content, interval=0.1),每个字符间隔0.1秒。 - 确保
pytest.txt和Python脚本在同一目录下,否则需填写完整文件路径。
内容的提问来源于stack exchange,提问作者Clark Wallace
相关产品推荐
相关产品推荐

