Как читать файл и записывать в текстовый файл?

Я хочу открыть файл mis, скопировать все данные и записать в текстовый файл.

мой файл mis.

имя файла – 1.mis

M3;3395;44;0;1;;20090404;094144;8193;3;0;;;;
M3;3397;155;0;2;;20090404;105941;8193;3;0;;;;
M3;3396;160;0;1;;20090404;100825;8193;3;0;;;;
M3;3398;168;0;2;;20090404;110106;8193;3;0;;;;

так далее...,

вышеуказанные данные должны отображаться в текстовом файле с тем же именем файла (1.формат txt.)

Я пробовал этот код.

Dim sFileText As String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:ClientsConverterClockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
Loop
Close #iFileNo

Open "C:ClientsConverter.txt" For Output As #iFileNo
Do While Not EOF(iFileNo)
Write #iFileNo, sFileText
Loop
Close #iFileNo

ничего не сохраняется в 1.формат txt.

4 ответов


гораздо проще использовать среду выполнения сценариев, которая установлена по умолчанию в Windows

просто перейдите в ссылку проекта и проверьте Microsoft Scripting Runtime и нажмите OK.

тогда вы можете использовать этот код, который намного лучше, чем команды файла по умолчанию

Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("C:\Clients\Converter.txt", ForWriting, True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

Что касается того, что не так с вашим исходным кодом здесь Вы читаете каждую строку текстового файла.

Input #iFileNo, sFileText

тогда здесь вы пишете это

Write #iFileNo, sFileText

sFileText является поэтому каждый раз, когда вы читаете, вы просто заменяете содержимое sFileText содержимым только что прочитанной строки.

поэтому, когда вы идете, чтобы написать его, все, что вы пишете, это последняя строка, которую Вы читаете, которая, вероятно, пустая строка.

Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo

iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo

Примечание вам не нужно делать цикл для записи. sFinal содержит полный текст файла, готовый для записи одним выстрелом. Обратите внимание, что вход считывает строку за раз, поэтому каждая строка добавляется к sFinal должен иметь CR и LF, добавленные в конце, чтобы быть правильно записаны в системе MS Windows. Другой операционной системе может просто понадобиться LF(Chr$(10)).

Если вам нужно обработать входящие данные, то вам нужно сделать что-то подобное.

Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection

iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo, sFileText
  C.Add sFileText
Loop
Close #iFileNo

For Each vTemp in C
     Process vTemp
Next sTemp

iFileNo = FreeFile
Open "C:\Clients\Converter.txt" For Output As #iFileNo
For Each vTemp in R
   Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo

Если вы хотите сделать это построчно:

Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer

iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile 
iOutputFile = FreeFile
Open "C:\Clients\Converter.txt" For Output As #iOutputFile 
Do While Not EOF(iInputFile)
   Line Input #iInputFile , sFileText
   ' sFileTextis a single line of the original file
   ' you can append anything to it before writing to the other file
   Print #iOutputFile, sFileText 
Loop
Close #iInputFile 
Close #iOutputFile 

FileCopy "1.mis", "1.txt"

    An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)

'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).


An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!

'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo

С здесь