vbs操作txt

上一篇 / 下一篇  2011-03-02 13:43:30 / 个人分类:VBS

1,写文本文件
Const ForReading = 1, ForWriting = 2
   Dim fso, f
   set fso=createobject("scripting.filesystemobject")
   set f=fso.opentextfile("c:\testfile.txt",ForWriting,true)
   f.write "hello"
   f.write "world"
   f.writeblanklines 2 第二行写入空白行
   f.writeline "worldhello"
   f.writeline "end"    写入并换行
   f.close
  
2.读文本文件
Const ForReading = 1, ForWriting = 2
   Dim fso, f
   set fso=createobject("scripting.filesystemobject")
   set f=fso.opentextfile("c:\testfile.txt",ForReading)
   readlinefile=f.readline '读取一行
   readfileindex=f.read(5) 读取5个字符
   readskipfile=f.ship(3)  跳过3个字符开始读取
   readskipfile2=f.read(2)从第四个字符开始读取2个字符
   readallfile=f.readall  读取所有字符
 
  ’f.skipline
   readsecondline=f.readline  读取第二行
   f.colse
  
  3.其他相关属性
  Const ForReading = 1
   Dim fso, theFile, retstring
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set theFile = fso.OpenTextFile("c:\testfile.txt", ForReading, False)
   Do While theFile.AtEndOfStream<> True  判断是不是文件流的结尾
      retstring = theFile.ReadLine   循环读取每一行
   Loop
   theFile.Close
   ReadEntireFile = retstring
  
   Const ForReading = 1
   Dim fso, theFile, retstring
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set theFile = fso.OpenTextFile(filespec, ForReading, False)
   Do While theFile.AtEndOfLine<> True  判断是否行结尾
      retstring = theFile.Read(1)  循环读取没一个字符
   Loop
   theFile.Close
 
 
 
   Const ForReading = 1
   Dim fso, theFile, lines
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile(filespec, ForReading, False)
   f.readall
   lines=f.line      ’返回行数
   columns=f.column  ‘返回列数,即最长一行的字符个数


另一种打开文件对象的方法

Function TextStreamTest

  Const ForReading = 1, ForWriting = 2, ForAppending = 8

  Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0

  Dim fso, f, ts

  Set fso = CreateObject("Scripting.FileSystemObject")

  Set f = fso.GetFile("c:\test1.txt")

  Set ts =f.OpenAsTextStream(ForWriting,TristateUseDefault)

  ts.Write "Hello World"

可写world,但读取时出现乱码

  ts.Close

  Set ts =f.OpenAsTextStream(ForReading,TristateUseDefault)

  TextStreamTest = ts.ReadLine

  ts.Close

End Function

 

 '创建文件

Sub CreateAfile

  Dim fso, MyFile

  Set fso = CreateObject("Scripting.FileSystemObject")

  Set MyFile = fso.CreateTextFile("c:\testfile.txt",True)

  MyFile.WriteLine("This is a test.")

  MyFile.Close

End Sub

 

'copymovedelete操作

Dim fso, MyFile

Set fso = CreateObject("Scripting.FileSystemObject")

Set MyFile = fso.GetFile("c:\testfile.txt")

MyFile.Copy ("c:\windows\desktop\test2.txt")

MyFile.move ("c:\windows\desktop\test2.txt")

MyFile.delete


TAG:

 

评分:0

我来说两句

日历

« 2024-05-13  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 28993
  • 日志数: 45
  • 文件数: 3
  • 建立时间: 2010-11-23
  • 更新时间: 2011-03-02

RSS订阅

Open Toolbar