【问题标题】:Read and write into a file using VBScript使用 VBScript 读取和写入文件
【发布时间】:2010-11-11 16:14:26
【问题描述】:

我们如何使用 VBScript 读取字符串并将其写入文本文件?我的意思是我有一个已经存在的文本文件,所以当我使用下面的代码时:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1) 

这只会打开文件以供阅读,但我无法写入任何内容 当我使用这段代码时:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)

我只能用这个文件来写,但不能读任何东西。无论如何,我们只需调用一次OpenTextFile 方法就可以打开文件进行读写。

我对 VBScript 真的很陌生。我只熟悉C概念。 是否有任何链接可以让我真正开始使用 VBScript?

我想我需要对对象和属性概念有很好的了解。

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    不要这么认为...您只能使用openTextFile 进行读取(1)、写入(2)或附加(8)。参考here。

    如果你是 VBScript 的 using VB6 instead,你可以这样做:

    Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber
    

    使用Random 模式。例如:

    Open "C:\New\maddy.txt" For Random As #1
    

    【讨论】:

    • 我对 vbscripting 很陌生。我只是熟悉我的 C 概念。任何人都可以建议我任何链接以真正开始我的 vbscripting。我想我需要对对象和属性概念有很好的了解。有什么建议吗??
    • 这是来自 W3Schools 的一个不错的教程:w3schools.com/Vbscript/vbscript_intro.asp
    • 钢琴家,非常感谢..我已经浏览了链接,只是告诉了基本操作。我想更深入一点,比如对象、类的使用。我真的对这些条款本身不熟悉。
    • 这里对这些术语进行了相当详细的解释:4guysfromrolla.com/webtech/092399-1.shtml
    【解决方案2】:

    您可以创建一个临时文件,然后将其重命名为原始文件:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    strTemp = "c:\test\temp.txt"
    Set objFile = objFS.GetFile(strFile)
    Set objOutFile = objFS.CreateTextFile(strTemp,True)
    Set ts = objFile.OpenAsTextStream(1,-2)
    Do Until ts.AtEndOfStream
        strLine = ts.ReadLine
        ' do something with strLine 
        objOutFile.Write(strLine)
    Loop
    objOutFile.Close
    ts.Close
    objFS.DeleteFile(strFile)
    objFS.MoveFile strTemp,strFile 
    

    使用OpenTextFile的用法几乎相同:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    strTemp = "c:\test\temp.txt"
    Set objFile = objFS.OpenTextFile(strFile)
    Set objOutFile = objFS.CreateTextFile(strTemp,True)    
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        ' do something with strLine 
        objOutFile.Write(strLine & "kndfffffff")
    Loop
    objOutFile.Close
    objFile.Close
    objFS.DeleteFile(strFile)
    objFS.MoveFile strTemp,strFile 
    

    【讨论】:

    • 唯一的一点是你应该使用objOutFile.WriteLine(Inp) 来输出相同的行。
    【解决方案3】:

    您可以打开两个文本流,一个用于阅读

    Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)
    

    一个用于附加

    Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)
    

    filestreamIN 可以从文件开头读取,filestreamOUT 可以写入文件末尾。

    【讨论】:

      【解决方案4】:

      你也可以读入整个文件,并将其存储在一个数组中

      Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",1)
      file = Split(filestreamIN.ReadAll(), vbCrLf)
      filestreamIN.Close()
      Set filestreamIN = Nothing
      

      以您选择的任何方式操作数组,然后将数组写回文件。

      Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",2,true)
      
      for i = LBound(file) to UBound(file)
          filestreamOUT.WriteLine(file(i))
      Next
      
      filestreamOUT.Close()
      Set filestreamOUT = Nothing 
      

      【讨论】:

      • 这是一种方法,只要文件不大。
      • 几乎是一个班轮,即你可以去 "file = Split(CreateObject(...).OpenTextFile(...,1).ReadAll(), vbCrLf)" :)跨度>
      【解决方案5】:

      在http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx 上查找有关 FileSystemObject 对象的更多信息。对于好的 VBScript,我建议:

      • Option Explicit 有助于检测变量中的拼写错误。
      • Function 和 Sub 以提高可读性和重用性
      • Const 以便为众所周知的常量命名

      下面是一些用于读取和写入文本到文本文件的代码:

      Option Explicit
      
      Const fsoForReading = 1
      Const fsoForWriting = 2
      
      Function LoadStringFromFile(filename)
          Dim fso, f
          Set fso = CreateObject("Scripting.FileSystemObject")
          Set f = fso.OpenTextFile(filename, fsoForReading)
          LoadStringFromFile = f.ReadAll
          f.Close
      End Function
      
      Sub SaveStringToFile(filename, text)
          Dim fso, f
          Set fso = CreateObject("Scripting.FileSystemObject")
          Set f = fso.OpenTextFile(filename, fsoForWriting)
          f.Write text
          f.Close
      End Sub
      
      SaveStringToFile "f.txt", "Hello World" & vbCrLf
      MsgBox LoadStringFromFile("f.txt")
      

      【讨论】:

      • 这两个函数都需要“f.Close”方法,这样文件就不会保持打开状态。
      • .ReadAll 似乎有其他方法没有的文件大小限制。或者至少我的脚本在超过 1GB 左右的文件上崩溃......
      • 不要对大文件使用ReadAll,而是使用TextStream对象来缓冲读/写。
      【解决方案6】:

      无论您尝试做什么,都不需要同时读取和写入文件。它还会使用更多的内存,这应该始终避免。我建议使用 .ReadAll 方法读取整个文件,然后关闭它并对数据执行任何您需要执行的操作(假设您将内容读入变量),然后写入同一个文件并覆盖该文件.如果您担心在覆盖当前文件时出现问题,您可以随时尝试将其写入其他文件,如果在尝试覆盖原始文件之前不起作用,则抛出错误。

      【讨论】:

        【解决方案7】:

        您可以将其放入 Excel 工作表中

         'this gives you an excel app
         oExcel = CreateObject("Excel.Application")
        
         'this opens a work book of your choice, just set "Target" to a filepath
         oBook = oExcel.Workbooks.Open(Target)
        
         'how to read
         set readVar = oExcel.Cell(1,1).value
         'how to write
         oExcel.Cell(1,2).value = writeVar
        
         'Saves & Closes Book then ends excel
         oBook.Save
         oBook.Close
         oExcel.Quit
        

        对不起,如果这个答案没有帮助,第一次写答案,只是觉得这对你来说可能是一个更好的方法

        【讨论】:

          【解决方案8】:

          以下是执行此操作的一些简单代码:

          sLocation = "D:\Excel-Fso.xls"
          sTxtLocation = "D:\Excel-Fso.txt"
          Set ObjExl = CreateObject("Excel.Application")
          Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
          Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
          ObjExl.Visible = True
          Set FSO = CreateObject("Scripting.FileSystemObject")
          Set FSOFile = FSO.CreateTextFile (sTxtLocation)
          sRowCnt = ObjWrkSht.usedRange.Rows.Count
          sColCnt = ObjWrkSht.usedRange.Columns.Count
          For iLoop = 1 to sRowCnt
            For jLoop = 1 to sColCnt 
              FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab 
            Next
          Next
          
          Set ObjWrkBk = Nothing
          Set ObjWrkSht = Nothing
          Set ObjExl = Nothing
          Set FSO = Nothing
          Set FSOFile = Nothing
          

          【讨论】:

          • 欢迎来到 Stack Overflow!请小心链接到您自己在不同网站上的内容,您不想成为spammer。您应该在此处包含大部分内容,并且仅将链接用作参考。
          【解决方案9】:

          这是为了创建一个文本文件

          For i = 1 to 10
              createFile( i )
          Next
          
          Public Sub createFile(a)
          
              Dim fso,MyFile
              filePath = "C:\file_name" & a & ".txt"
              Set fso = CreateObject("Scripting.FileSystemObject")
              Set MyFile = fso.CreateTextFile(filePath)
              MyFile.WriteLine("This is a separate file")
              MyFile.close
          
          End Sub
          

          这用于读取文本文件

          Dim fso
          Set fso = CreateObject("Scripting.FileSystemObject")
          Set dict = CreateObject("Scripting.Dictionary")
          Set file = fso.OpenTextFile ("test.txt", 1)
          row = 0
          Do Until file.AtEndOfStream
            line = file.Readline
            dict.Add row, line
            row = row + 1
          Loop
          
          file.Close
          
          For Each line in dict.Items
            WScript.Echo line
            WScript.Sleep 1000
          Next
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-03-08
            • 2015-07-26
            • 2019-01-24
            • 2011-10-28
            • 2011-01-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多