📂 Python File Handling
Estimated reading: 4 minutes 346 views

Python File Methods – Read, Write, Seek, Flush Explained

Introduction – Why Learn File Methods in Python?

Once a file is opened using open(), Python provides several built-in methods to efficiently interact with that file. These file object methods allow you to read, write, navigate, and manage file content—making them crucial for applications that handle logs, data files, or configuration files.

In this guide, you’ll learn:

  • Key file object methods like read(), write(), seek(), and tell()
  • How and when to use each method
  • Best practices for safe file manipulation

Opening a File

f = open("example.txt", "r")

This returns a file object, which gives access to all file methods.


Essential Python File Methods

MethodDescription
read([size])Reads entire file or up to size bytes
readline()Reads a single line
readlines()Reads all lines into a list
write(str)Writes a string to the file
writelines(lines)Writes a list of strings
seek(offset)Moves the cursor to a specific byte position
tell()Returns the current cursor position
flush()Flushes internal buffer to file immediately
close()Closes the file

Python File Methods with Examples

read() – Read Entire File or N Bytes

with open("sample.txt", "r") as f:
    print(f.read(10))  # Reads first 10 characters

Use read() to read the file’s content (or a portion of it).


readline() – Read One Line at a Time

with open("sample.txt", "r") as f:
    print(f.readline())

Use inside loops for memory-efficient reading of large files.


readlines() – Read All Lines into a List

with open("sample.txt", "r") as f:
    lines = f.readlines()
    print(lines)

Useful when you need to process lines as a list.


write() – Write Text to File

with open("output.txt", "w") as f:
    f.write("Hello, World!")

Writes string data. Overwrites file if in 'w' mode.


writelines() – Write List of Strings

lines = ["Line1\n", "Line2\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

Doesn’t add line breaks automatically—include \n manually.


Navigation & File Pointer Methods

tell() – Get Cursor Position

with open("sample.txt", "r") as f:
    print(f.tell())  # Outputs current byte offset

Useful for debugging or managing binary data.


seek(offset) – Move Cursor

with open("sample.txt", "r") as f:
    f.seek(5)
    print(f.read())

Moves the cursor 5 bytes from the beginning.


💨 flush() – Force Write to Disk

with open("log.txt", "w") as f:
    f.write("Data logged.")
    f.flush()

Immediately writes buffered content to disk.


close() – Always Close the File

f = open("sample.txt", "r")
f.close()

Frees system resources. Use with open() to auto-close safely.


Best Practices

  • Always use with open() to auto-close files.
  • Use flush() when writing logs or data frequently.
  • Use seek() and tell() when you need precise control over the cursor (e.g., binary files).
  • Don’t mix reading and writing in a file unless you use the correct mode (r+, w+, etc.).

Summary – Recap & Next Steps

Python’s file object methods give you full control over file reading, writing, and navigation. These are essential for building real-world applications that process text, logs, configurations, or binary data.

Key Takeaways:

  • Use read(), readline(), and readlines() to read data in various formats.
  • Use write() and writelines() to output data to files.
  • Use seek() and tell() to control the file pointer.
  • Use flush() to ensure data is saved immediately.

Real-World Relevance:
File methods are widely used in data engineering, log monitoring, machine learning pipelines, and backend development.


FAQ Section – Python File Methods

What does seek() do in file handling?

It moves the file pointer to a specific position.

What’s the difference between write() and writelines()?

write() adds a single string. writelines() adds a list of strings—no automatic line breaks.

How can I read a large file without using too much memory?

Use readline() in a loop:

for line in f:
    process(line)

When should I use flush()?

When writing to log files or when frequent writes must be saved immediately.

What happens if I forget to close a file?

May cause memory leaks or file corruption. Use with open() for safe automatic closing.


Share Now :
Share

Python File Methods

Or Copy Link

CONTENTS
Scroll to Top