How do I check end of file (EOF) in python?

How do I check end of file (EOF) in python?  Awantik Das
Posted on May 22, 2017, 12:47 p.m.

python end of file

Assuming 'a.txt' contains some lines like

-------------------------------------

This is a nice world to live.

But I am not sure of many good things

--------------------------------------

x = 0
with open('a.txt') as f:
   f.readlines()
   x = f.tell()

f = open('a.txt','a')
f.seek(x)
f.write('Again Hello World')

readlines() reads the entire file & reaches the end.

f.tell() returns current location of the file pointer, which is at the end.

To cross-validate, open the file again with open(), reach the end of file using seek(x) & write there

File contents now

------------------------------------

This is a nice world to live.

But I am not sure of many good things
Again Hello World

---------------------------------------------


Awantik Das is a Technology Evangelist and is currently working as a Corporate Trainer. He has already trained more than 3000+ Professionals from Fortune 500 companies that include companies like Cognizant, Mindtree, HappiestMinds, CISCO and Others. He is also involved in Talent Acquisition Consulting for leading Companies on niche Technologies. Previously he has worked with Technology Companies like CISCO, Juniper and Rancore (A Reliance Group Company).




Keywords : Python File-IO


Recommended Reading


How should I start learning Python?

Python is a powerful, flexible, open source language that is easy to learn, easy to use, and has powerful libraries for data manipulation and analysis. Python has a unique combination of being both a capable general-purpose programming language as well as b...


Object Model in Python - Understanding Internals

The object model of Python is something very less discussed but important to understand what happens under the cover. Understanding this before diving into python makes journey smooth


Deep Dive into Understanding Functions in Python

Python provides very easy-to-use syntaxes so that even a novice programmer can learn Python and start delivering quality codes.It gives a lot of flexibility to programmers to make the code more reusable, readable and compact. To know more about what are the...


What is future prospects of being a Django developer in India?

Apart from Training Django, due to increasing corporate requirement I am given assignments to interview candidates for Python & Django. Sharing my understanding of entire scenario from candidates prospective or corporate .