Description
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.
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+'].
If the file is opened in text mode using 't', only offsets returned by tell[] are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
Syntax
Following is the syntax for seek[] method −
fileObject.seek[offset[, whence]]
Parameters
offset − This is the position of the read/write pointer within the file.
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.
Return Value
This method does not return any value.
Example
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 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th 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[]
When we run above program, it produces following result −
Name of the file: foo.txt Read Line: Python is a great language. Read Line: Python is a great language.
python_files_io.htm
I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' .
This is the code I have for that:
fhand = open['mbox.txt']
count = 0
for line in fhand:
count = count + 1
print count
for line in fhand:
if line.startswith['From: ']:
print line
I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file?
Thank you for your help.
asked Oct 12, 2016 at 17:21
file.seek[0]
seek[] takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file.
answered Oct 12, 2016 at 17:23
1
Try this out :
with open['mbox.txt'] as f:
count = 0
for l in f.readlines[]:
count += 1
if l.startswith['From: ']:
print l
To get back to start of file use seek[0]
answered Oct 12, 2016 at 17:23
MMFMMF
5,5423 gold badges15 silver badges19 bronze badges
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
The concept of file handling is used to preserve the data or information generated after running the program. Like other programming languages like
C, C++, Java, Python also support file handling.
Refer the below article to understand the basics of File Handling.
- File Handling in Python.
- Reading and Writing to files in Python
seek[] method
In Python, seek[] function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file.
Syntax: f.seek[offset, from_what], where f is file pointer
Parameters:
Offset: Number of positions to move forward
from_what: It defines point of reference.
Returns: Return the new absolute position.
The reference point is selected by the from_what argument. It accepts three values:
- 0: sets the reference point at the beginning of the file
- 1: sets the reference point at the current file position
- 2:
sets the reference point at the end of the file
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."
Python3
f
=
open
[
"GfG.txt"
,
"r"
]
f.seek[
20
]
print
[f.tell[]]
print
[f.readline[]]
f.close[]
Output:
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.'
Python3
f
=
open
[
"data.txt"
,
"rb"
]
f.seek[
-
10
,
2
]
print
[f.tell[]]
print
[f.readline[].decode[
'utf-8'
]]
f.close[]