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

VBScript读取文件夹文本写入outfile时循环无法终止的问题求助

VBS遍历文本文件并合并内容的循环问题解决

你的代码出现循环无法终止、重复处理的核心原因是:你创建的输出文件testout.txt被包含在目标文件夹的遍历范围内,当For Each file in folder.Files执行时,刚生成的输出文件会被当成新的待处理文件,导致循环反复执行。

修正方案

  • 将输出文件放在目标文件夹之外,彻底避免被遍历到
  • 遍历文件时添加过滤规则,只处理.txt后缀的文本文件,同时排除输出文件本身

修正后的代码

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
' 定义目标文件夹路径
Dim folderPath : folderPath = "C:\Precious\Projects\Sources\VBS\Testing"
' 将输出文件放在目标文件夹外,避免被遍历
Dim outFilePath : outFilePath = "C:\Precious\Projects\Sources\VBS\testout.txt"

Set folder = objFSO.GetFolder(folderPath)
Set outfile = objFSO.CreateTextFile(outFilePath)

For Each file in folder.Files
    ' 过滤条件:仅处理txt文件,且跳过输出文件
    If LCase(objFSO.GetExtensionName(file.Path)) = "txt" And file.Path <> outFilePath Then
        Set testfile = objFSO.OpenTextFile(file.Path, ForReading)
        
        Do While Not testfile.AtEndOfStream
            line = testfile.ReadLine
            outfile.WriteLine(line)
        Loop
        
        testfile.Close
    End If
Next

outfile.Close

说明

  1. 路径变量化,方便后续修改维护
  2. 双重过滤规则既保证只处理文本文件,又避免误读输出文件,彻底解决循环重复问题
  3. 保留了你原本的逐行读取写入逻辑,确保文件内容完整合并

内容的提问来源于stack exchange,提问作者Precious P.nkuna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:23:36