Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines from a text file but skip the first two lines

I've got this macro code in Microsoft Office Word 2003 which reads the lines of a text file. The lines each represent a string value that I need to use later in the code.

However, the first two lines of the text file contains some stuff that I don't need. How can I modify the code so that it skips the two first lines? The "Intellisense" within the VBA editor in Word sucks hard btw..

Anyway, the code looks something like this

Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String

sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
    MsgBox ("Cannot find fields.ini")
End If

iFileNum = FreeFile()
Open sFileName For Input As iFileNum
Do While Not EOF(iFileNum)
    Line Input #iFileNum, Fields

    MsgBox (Fields)

And this code currently gives me all of the lines, and I don't want the first two.

like image 828
Kenny Bones Avatar asked Jun 02 '09 10:06

Kenny Bones


People also ask

How do I skip the first line of a text file?

You can use p. readline() or next(readline) to skip a line, before you loop over the remaining lines. This will read a line, and then just throw it away.

How do you skip to the next line in text?

To add spacing between lines or paragraphs of text in a cell, use a keyboard shortcut to add a new line. Click the location where you want to break the line. Press ALT+ENTER to insert the line break.

Why is readline () skipping the first line Python?

You simply discarded the first line from fp. readline() which explains the "skip". readline returns an empty string at end of file which explains the exception (mostly - you also may want to account for lines that only have a new line).

How do you skip two lines in Python?

There are many ways in which you can skip a line in python. Some methods are: if, continue, break, pass, readlines(), and slicing.


2 Answers

That whole Open <file path> For Input As <some number> thing is so 1990s. It's also slow and very error-prone.

In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:

With New Scripting.FileSystemObject
    With .OpenTextFile(sFilename, ForReading)

        If Not .AtEndOfStream Then .SkipLine
        If Not .AtEndOfStream Then .SkipLine

        Do Until .AtEndOfStream
            DoSomethingImportantTo .ReadLine
        Loop

    End With
End With
like image 165
Mike Woodhouse Avatar answered Oct 27 '22 00:10

Mike Woodhouse


You can use random access.

Open "C:\docs\TESTFILE.txt" For Random As #1 

    Position = 3    ' Define record number.
    Get #1, Position, ARecord    ' Read record.

Close #1
like image 22
Fionnuala Avatar answered Oct 26 '22 23:10

Fionnuala