python file seek skips lines

  • Last Update :
  • Techknowledgy :

The simplest (and safest - it ensures your file gets closed properly) way would be to use a with construct, and readline()

print "Register CIP_REGS_CONTROL value:"
with open('test1', 'r') as f:
   for i in range(4):
   print f.readline().strip()

Suggestion : 2

Python file method seek() sets the file's current position at the offset. The whence argument is optional and defaults to 0, which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.,whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.,There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.,If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode 'a+').

Following is the syntax for seek() method −

fileObject.seek(offset[, whence])

The following example shows the usage of seek() method.

Python is a great language
Python is a great language

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1 st line
# This is 2n d line
# This is 3 rd line
# This is 4 th line
# This is 5 th line

line = fo.readline()
print "Read Line: %s" % (line)

# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file
fo.close()

Suggestion : 3

Last Updated : 28 Apr, 2022

By default from_what argument is set to 0.
Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to 0.
Example 1: Let’s suppose we have to read a file named “GfG.txt” which contains the following text: 
 

"Code is like humor. When you have to explain it, it’s bad."

20
When you have to explain it, it’ s bad.

Example 2: Seek() function with negative offset only works when file is opened in binary mode. Let’s suppose the binary file contains the following text.
 

b 'Code is like humor. When you have to explain it, its bad.'

20
When you have to explain it, it’ s bad.

47, its bad.

Suggestion : 4

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin and the optional arguments mode and openhook are ignored. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.,Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty.,All files are opened in text mode by default, but you can override this by specifying the mode parameter in the call to input() or FileInput. If an I/O error occurs during opening or reading a file, OSError is raised.,This module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open().

import fileinput
for line in fileinput.input(encoding = "utf-8"):
   process(line)
with fileinput.input(files = ('spam.txt', 'eggs.txt'), encoding = "utf-8") as f:
   for line in f:
   process(line)
with FileInput(files = ('spam.txt', 'eggs.txt')) as input:
   process(input)

Suggestion : 5

We use the sample.txt file to read the contents. This method uses next() to skip the header and starts reading the file from line 2.,Note: If you want to print the header later, instead of next(f) use f.readline() and store it as a variable or use header_line = next(f). This shows that the header of the file is stored in next().,In this article, we learned to read file contents from line 2 by using several built-in functions such as next(), readlines(), islice(), csv.reader() and different examples to skip the header line from the given files.,We use the sample.csv file to read the contents. This method reads the file from line 2 using csv.reader that skips the header using next() and prints the rows from line 2. This method can also be useful while reading the content of multiple CSV files.

Sample Text File //sample.txt

Student Details of Class X
David, 18, Science
Amy, 19, Commerce
Frank, 19, Commerce
Mark, 18, Arts
John, 18, Science

Sample CSV File //sample.csv

Student Details of Class X
David 18 Science
Amy 19 Commerce
Frank 19 Commerce
Mark 18 Arts
John 18 Science

Note: If you want to print the header later, instead of next(f) use f.readline() and store it as a variable or use header_line = next(f). This shows that the header of the file is stored in next().

#opens the file
with open("sample.txt") as f:
   #start reading from line 2
next(f)
for line in f:
   print(line)

#closes the file
f.close()

We use the sample.txt file to read the contents. This method imports islice from itertools module in Python. islice() takes three arguments. The first argument is the file to read the data, the second is the position from where the reading of the file will start and the third argument is None which represents the step. This is an efficient and pythonic way of solving the problem and can be extended to an arbitrary number of header lines. This even works for in-memory uploaded files while iterating over file objects.

from itertools
import islice

#opens the file
with open("sample.txt") as f:
   for line in islice(f, 1, None):
   print(line)

#closes the file
f.close()

We use the sample.csv file to read the contents. This method reads the file from line 2 using csv.reader that skips the header using next() and prints the rows from line 2. This method can also be useful while reading the content of multiple CSV files.

import csv

#opens the file
with open("sample.csv", 'r') as r:
   next(r)
#skip headers
rr = csv.reader(r)
for row in rr:
   print(row)