You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遇ValueError: I/O operation on closed file,如何用pyautogui输入pytest.txt内容?

问题解决:ValueError: I/O operation on closed file 及文本输入实现

错误原因

你存在两个核心问题:

  • 直接将文件对象赋值给了characters,with代码块执行结束后会自动关闭文件,后续操作这个已关闭的文件对象就会触发ValueError。
  • 误用pyautogui.press():该函数用于模拟单个按键按下,无法直接输入字符串或文本行,输入文本应该用pyautogui.typewrite()。

修正方案

  1. 在with块内读取文件实际内容,而非保存文件对象:
    • 用text.read()读取全部内容(适合一次性输入)
    • 用text.readlines()按行读取(适合逐行输入)
  2. 替换pyautogui.press()为pyautogui.typewrite()实现文本输入
  3. 简化循环和变量逻辑,删除冗余代码

完整修正代码

方案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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:07:16