- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the current open file line in Python?
Python doesn't support this directly. You could write a wrapper class for it. For example,
class FileLineWrapper(object): def __init__(self, file): self.f = file self.curr_line = 0 def close(self): return self.f.close() def readline(self): self.curr_line += 1 return self.f.readline() # to allow using in 'with' statements def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close()
And use the above code as:
f = FileLineWrapper(open("my_file", "r")) f.readline() print(f.line)
This will give the output: 1
There are other methods to keep track of the line number if you are only using the readline method. For example,
f=open("my_file", "r") for line_no, line in enumerate(f): print line_no f.close()
- How to get the system configuration information relevant to an open file using Python?
- How to open a file to write in Python?
- How to open a file just to read in python?
- How to get full path of current file's directory in Python?
- How to open a file in binary mode with Python?
- How to open a file in append mode with Python?
- How to know the current position within a file in Python?
- How to open a file in the same directory as a Python script?
- How to read complete text file line by line using Python?
- How to open a binary file in append mode with Python?
- How to open hidden file using C#?
- Get the String representation of the current File object in Java
- How to open MySQL command line on Windows10?
- How to open a file in read and write mode with Python?
- How to get current time in milliseconds in Python?