使用VBScript读取和写入文件

时间:2021-08-11 01:35:01

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-

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

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

This opens the file only for reading but I am unable to write anything and when I use this code:-

这打开文件只是为了阅读,但我无法写任何东西,当我使用这段代码时: -

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

I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.

我可以使用这个文件写,但无法读取任何内容。无论如何,通过只调用一次OpenTextFile方法,我们可以打开文件进行读写。

I am really new to VBScript. I am only familiar with C concepts. Is there any link to really get me started with VBScript?

我是VBScript的新手。我只熟悉C概念。是否有任何链接真正让我开始使用VBScript?

I guess I need to have a good knowledge of the objects and properties concepts.

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

9 个解决方案

#1


You can create a temp file, then rename it back to original file:

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

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 

Usage is almost the same using OpenTextFile:

使用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 

#2


Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:

有关FileSystemObject对象的更多信息,请访问http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx。为了获得好的VBScript,我建议:

  • Option Explicit to help detect typos in variables.
  • 选项显式有助于检测变量中的拼写错误。

  • Function and Sub to improve readilbity and reuse
  • 功能和Sub可提高读取性和重用性

  • Const so that well known constants are given names
  • Const使得众所周知的常量被赋予名称

Here's some code to read and write text to a text file:

这里有一些代码用于读取和写入文本文件:

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")

#3


You could open two textstreams, one for reading

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

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

and one for appending

和一个附加

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

The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

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

#4


Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.

不要这么认为......你只能使用openTextFile来阅读(1),写(2)或追加(8)。参考这里。

If you were using VB6 instead of VBScript, you could do:

如果你使用VB6而不是VBScript,你可以这样做:

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

Using the Random mode. For example:

使用随机模式。例如:

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

#5


You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the

您可以把它放在Excel工作表中,如果它对你有用,如果它需要用于其他东西但是在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

sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you

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

#6


You could also read the entire file in, and store it in an array

您还可以读取整个文件,并将其存储在数组中

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

Manipulate the array in any way you choose, and then write the array back to the file.

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

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 

#7


Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.

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

#8


Below is some simple code to execute this:

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

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

#9


This is for create a text file

这是用于创建文本文件

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

And this for read a text file

这用于读取文本文件

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

#1


You can create a temp file, then rename it back to original file:

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

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 

Usage is almost the same using OpenTextFile:

使用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 

#2


Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:

有关FileSystemObject对象的更多信息,请访问http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx。为了获得好的VBScript,我建议:

  • Option Explicit to help detect typos in variables.
  • 选项显式有助于检测变量中的拼写错误。

  • Function and Sub to improve readilbity and reuse
  • 功能和Sub可提高读取性和重用性

  • Const so that well known constants are given names
  • Const使得众所周知的常量被赋予名称

Here's some code to read and write text to a text file:

这里有一些代码用于读取和写入文本文件:

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")

#3


You could open two textstreams, one for reading

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

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

and one for appending

和一个附加

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

The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

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

#4


Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.

不要这么认为......你只能使用openTextFile来阅读(1),写(2)或追加(8)。参考这里。

If you were using VB6 instead of VBScript, you could do:

如果你使用VB6而不是VBScript,你可以这样做:

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

Using the Random mode. For example:

使用随机模式。例如:

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

#5


You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the

您可以把它放在Excel工作表中,如果它对你有用,如果它需要用于其他东西但是在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

sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you

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

#6


You could also read the entire file in, and store it in an array

您还可以读取整个文件,并将其存储在数组中

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

Manipulate the array in any way you choose, and then write the array back to the file.

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

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 

#7


Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.

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

#8


Below is some simple code to execute this:

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

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

#9


This is for create a text file

这是用于创建文本文件

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

And this for read a text file

这用于读取文本文件

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