2009-09-10 15 views
7

Quiero abrir mis archivos, copiar todos los datos y escribir en un archivo de texto.¿Cómo leer un archivo y escribir en un archivo de texto?

Mi archivo mis.

Nombre de archivo - 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;;;; 

así sucesivamente ...,

Los datos anteriores deben aparecer en un archivo de texto con el mismo nombre de archivo (1.txt).

He intentado este código.

Dim sFileText 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 
Loop 
Close #iFileNo 

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

No se guarda nada en 1.txt.

+1

Bueno, si su mal almacena el archivo de datos como texto, sólo podría copiar el archivo a 1.txt ... :-) –

+2

no hay nada en 1.txt porque está escrito a 2.txt ... –

Respuesta

13

Es mucho más fácil de utilizar el tiempo de ejecución de secuencias de comandos que se instala de forma predeterminada en Windows

Simplemente diríjase a Referencia del proyecto y compruebe Microsoft Scripting Runtime y haga clic en Aceptar.

continuación, puede utilizar este código, que es mucho mejor que el archivo predeterminado comandos

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\2.txt", ForWriting, True) 
    TS.Write Final 
TS.Close 
Set TS = Nothing 
Set FSO = Nothing 

En cuanto a lo que está mal con su código original aquí que está leyendo cada línea del archivo de texto.

Input #iFileNo, sFileText 

Entonces aquí se escribe fuera

Write #iFileNo, sFileText 

sFileText es una variable de cadena así que lo que está sucediendo es que cada vez que lea, que acaba de reemplazar el contenido de sFileText con el contenido de la línea que acabo de leer.

Así que cuando va a escribirlo, todo lo que está escribiendo es la última línea que lee, que probablemente sea una línea en blanco.

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\2.txt" For Output As #iFileNo 
Write #iFileNo, sFinal 
Close #iFileNo 

Tenga en cuenta que no necesita hacer un bucle para escribir. sFinal contiene el texto completo del archivo listo para escribirse de una vez. Tenga en cuenta que la entrada lee una LÍNEA a la vez, por lo que cada línea anexa a sFinal necesita tener un CR y LF adjuntos al final para que se escriban correctamente en un sistema MS Windows. Otro sistema operativo puede necesitar una LF (Chr $ (10)).

Si necesita procesar los datos entrantes, debe hacer algo como esto.

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\2.txt" For Output As #iFileNo 
For Each vTemp in R 
    Write #iFileNo, vTemp & vbCRLF 
Next sTemp 
Close #iFileNo 
+0

Algunas computadoras de usuario no tienen FileSystemObject (he experimentado esto). Creo que los departamentos de TI excesivamente celosos a veces pisotean el tiempo de ejecución de secuencias de comandos por temor a los virus – MarkJ

+0

Sí, y por eso debe incluirlo como parte de su instalación. El sysop puede decidir si hacer una excepción para la aplicación. O haga su propia versión envolviendo la función nativa o envuelva el equivalente de .NET. Ambos son excesivos IMO. –

2
FileCopy "1.mis", "1.txt" 
+0

La copia de archivo está funcionando, supongamos que quiero agregar algo en un archivo de texto de destino, Cómo hacer código. – Gopal

2
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 

De Here

+0

Ver, @Gopal: Arriba Los mismos ** datos ** deben aparecer en un archivo de texto con lo mismo. Él/Ella necesita una FileCopy. – adatapost

+0

@Khenu - En un archivo fuente estoy teniendo n número de líneas, ¿cómo hacer un código? – Gopal

3

Si desea hacerlo línea por línea:

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\2.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 
Cuestiones relacionadas