从几个 .txt 文件中读取一行并将它们写入创建的文件中

编程入门 行业动态 更新时间:2024-10-26 06:29:33
本文介绍了从几个 .txt 文件中读取一行并将它们写入创建的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个非常简单的任务.

I have a quite simple task.

有一个文件夹,其中包含多个具有不同扩展名的文件.我需要制作一个脚本,它会在这个文件夹中找到所有扩展名为 .txt 的文件,从每个文件中读取第一行,然后在新创建的文件中写入所有第一行.

There is a folder which contains several files with different extensions. I need to make a script which will find all files with .txt extension in this folder, read first line from every file and then write all first lines in newly created file.

现在,我已经结束了这样的事情:

For now, I've ended up with something like this:

Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim f, colFiles , objFile
Dim tFolder, tFile
Dim lineToCopy, fileContents
Dim input, output

Set tFolder = fso.GetFolder("C:\Temp")
Set tFile = tFolder.CreateTextFile("test.txt", true) 

Set f = fso.GetFolder("D:\Folder")
Set colFiles = f.Files
    For Each objFile in colFiles
        If LCase(fso.GetExtensionName(objFile.name)) = "txt" Then
            Set input = fso.OpenTextFile(LCase(objFile.name))
            If Not input.AtEndofStream Then lineToCopy = input.ReadLine
            input.close
            output = fso.OpenTextFile(tFolder, True)
            output.WriteLine lineToCopy
            output.close
        End If
    Next

WScript.sleep 60000000

激活后,.vbs 文件告诉我他找不到该行中的文件:

When activated, .vbs file tells me he couldn't find the file from that line:

Set input = fso.OpenTextFile(LCase(objFile.name))

我想这是因为 IF LCASE<...> 块无法将文件夹内容理解为 .txt 文件.我哪里错了,需要做些什么来解决这个问题?

I suppose that happens because IF LCASE<...> block doesn't understand folder contents as .txt files. Where am I wrong and what is needed to be done to solve that problem?

请放心,理查德

推荐答案

将文件的完整 .Path 用于 OpenTextFile 或通过 OpenAsTextStream 获取流.使用 tFile 而不是重复创建输出.删除所有风险/货物崇拜脂肪:

Use the full .Path of the file for OpenTextFile or get the stream via OpenAsTextStream. Use tFile instead of repeatedly creating output. Delete all the risky/cargo cult fat:

Option Explicit

Dim fso   : Set fso = CreateObject("Scripting.FileSystemObject")
Dim tFile : Set tFile = fso.CreateTextFile(fso.BuildPath(".\", "test.txt"))
Dim oFile

For Each oFile in fso.GetFolder("..\data").Files
    If LCase(fso.GetExtensionName(oFile.Path)) = "txt" Then
'      Dim input: Set input = fso.OpenTextFile(LCase(oFile.Path))
       Dim input: Set input = oFile.OpenAsTextStream()
       If Not input.AtEndofStream Then tFile.WriteLine input.ReadLine()
       input.Close
    End If
Next

tFile.Close

这篇关于从几个 .txt 文件中读取一行并将它们写入创建的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 00:25:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1164483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几个   文件   并将   txt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!