vbs代码删除文本文件中的指定行
下面是一个示例的VBS代码,它可以删除文本文件中的指定行。你可以根据需要修改代码中的文件路径和要删除的行号。
Const ForReading = 1
Const ForWriting = 2
Dim filePath, lineNumber, objFSO, objFile, objTextStream, content, lines, i
' 文件路径
filePath = "C:\path\to\your\file.txt"
' 要删除的行号
lineNumber = 3
' 创建文件系统对象
Set objFSO = CreateObject("Scripting.FileSystemObject")
' 打开文件
Set objFile = objFSO.OpenTextFile(filePath, ForReading)
' 读取文件内容
content = objFile.ReadAll
' 关闭文件
objFile.Close
' 按行分割文件内容
lines = Split(content, vbCrLf)
' 删除指定行
If lineNumber > 0 And lineNumber <= UBound(lines) + 1 Then
For i = lineNumber - 1 To UBound(lines) - 1
lines(i) = lines(i + 1)
Next
' 移除最后一行
ReDim Preserve lines(UBound(lines) - 1)
End If
' 打开文件以写入模式
Set objTextStream = objFSO.OpenTextFile(filePath, ForWriting)
' 写入修改后的内容
objTextStream.Write Join(lines, vbCrLf)
' 关闭文件
objTextStream.Close
请确保在运行脚本之前备份好你的文本文件,以防意外情况
原文地址: https://www.cveoy.top/t/topic/iyyK 著作权归作者所有。请勿转载和采集!