使用 VBScript 读取和写入文件

问题描述 投票:0回答:10

我们如何使用 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
10个回答
23
投票

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

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 

13
投票

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

  • Option Explicit 帮助检测变量中的拼写错误。
  • FunctionSub 提高可读性和重用性
  • 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")

6
投票

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

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

还有一个用于追加

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

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


6
投票

不这么认为...您只能使用

openTextFile
进行阅读 (
1
)、写作 (
2
) 或追加 (
8
)。参考这里

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

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

使用

Random

 模式。例如:

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

2
投票
您可以将其放入 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

很抱歉,如果这个答案没有帮助,第一次写答案,只是认为这对你来说可能是一个更好的方法


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

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
    

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


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

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
    

0
投票
这是为了创建一个文本文件

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
    

0
投票
下面是使用 VBScript 类似 Python 的方式来读写文件。您需要

TextIOBaseLite,可从 github 免费获得。

这里是如何阅读。

dim ofichier : set ofichier = open("C:\exemple.txt", "r", "utf-8", "\r\n") dim lignes, i lignes = ofichier.readlines() For i = 0 To UBound(lignes) WScript.Echo lignes(i) Next
ofichier.seek(0)
WScript.Echo ofichier.readline()

这里怎么写

dim ofichier : set ofichier = open ("C:\exemple2.txt", "w", "utf-8", "\r\n") ofile.write("content 1\n") ofile.write("more content") ofile.close()
    
© www.soinside.com 2019 - 2024. All rights reserved.