文本操作常用代码~

文件操作

创建文本文件

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:/FSO/ScriptLog.txt")

检察文件是否存在

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("C:/FSO/ScriptLog.txt") Then
    Set objFolder = objFSO.GetFile("C:/FSO/ScriptLog.txt")
Else
    Wscript.Echo "File does not exist."
End If

删除文本文件

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile("C:/FSO/ScriptLog.txt")

重命名文件

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:/FSO/ScriptLog.txt" , "C:/FSO/BackupLog.txt"

文本操作

读取全部内容

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:/Scripts/Test.txt", ForReading)

strContents = objFile.ReadAll
objFile.Close

一行行的读取文本文件内容

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile ("c:/scripts/servers.txt", ForReading)

Do Until objTextFile.AtEndOfStream
    strComputer = objTextFile.ReadLine
    Wscript.Echo strComputer
Loop

objTextFile.Close

追加文本文件一行内容

Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile ("C:/Scripts/Service_Status.txt", ForAppending, True)
objTextFile.WriteLine("追加的内容")
objTextFile.Close

有用的几个函数:

替换:将Jim替换成James。

strNewText = Replace(strText, "Jim ", "James ")

用逗号分隔字符串:

arrpath=split(strDN,",")
wscript.echo arrpath(0)

几个实例:

读取文本文件指定的行内容(读第四行内容存到strLine变量中)

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile("mylogfile.log", ForReading)

For i = 1 to 3 objTextFile.ReadLine Next

strLine = objTextFile.ReadLine Wscript.Echo strLine

objTextFile.Close

对文本文件中的项计数

On Error Resume Next

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

strPathtoTextFile = "C:/Scripts"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & strPathtoTextFile & ";" & _
        "Extended Properties=""text;HDR=Yes;FMT=Delimited"""

strFile = "City_Names.txt"

objRecordset.Open "Select City, Count(City) AS CountOfCity FROM " & strFile & _
    " GROUP BY City", objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    Wscript.Echo objRecordset.Fields.Item("City"), objRecordset.Fields.Item("CountOfCity")
    objRecordset.MoveNext
Loop
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值