Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python, how to read a file starting at the seventh line ?

Tags:

python

file-io

I have a text file structure as:

date
downland

user 

date data1 date2
201102 foo bar 200 50
201101 foo bar 300 35

So first six lines of file are not needed. filename:dnw.txt

f = open('dwn.txt', 'rb')

How do I "split" this file starting at line 7 to EOF?

like image 393
Merlin Avatar asked Feb 01 '11 15:02

Merlin


People also ask

How do I read a specific part of a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.


1 Answers

with open('dwn.txt') as f:
    for i in xrange(6):
        f, next()
    for line in f:
        process(line)

Update: use next(f) for python 3.x.

like image 180
John Machin Avatar answered Oct 27 '22 00:10

John Machin