PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » File Handling » File Objects in Python

File Objects in Python

Updated on: December 4, 2026 | 1 Comment

In this tutorial, you’ll learn about file objects in Python. You’ll also see how to use file object methods and attributes to perform various file operations.

Series: Python File Handling

Table of contents

  • What is the File Object?
  • Types of File Object
    • Text files (TextIOWrapper)
    • Binary Files (BufferedReader and BufferedWriter)
    • Raw Files
  • File Object Attributes
  • File Object Methods
    • read() Method
    • readline() Method
    • readlines() Method
    • readable() Method
    • truncate(size) Method
    • write() Method
    • writelines() Method
    • writable() Method
    • close() Method
    • seek() and tell() Methods
    • fileno() Method
    • flush() Method
    • isatty() Method
  • Iterate Over a File Object
  • Summary

What is the File Object?

A Python file object provides methods and attributes to access and manipulate a file. Using file objects, you can read from or write to any file.

Whenever you open a file to perform any operation on it, Python returns a file object. The most common way to create a file object is the built-in open() function.

An OSError exception (formerly called IOError) is raised when a file operation fails for an I/O-related reason, for example, when the file doesn’t exist. If you misuse a file object, for example, by trying to write to a file that is opened in read-only mode, Python raises io.UnsupportedOperation.

Types of File Object

In Python, there are three different categories of a file object, which are listed below:

  1. Text files
  2. Binary files
  3. Raw files

All file types objects are defined in the io module.

Text files (TextIOWrapper)

The text file type is the most common. Text files store characters, such as plain text, CSV data, or source code, with no special formatting.

Open a text file using the open() function in text mode, for example, open('test.txt', 'r'). Text mode is the default. Opening a text file returns a TextIOWrapper file object, which reads and writes strings.

Example

file = open('test.txt', 'w')
print(type(file))
# Output: <class '_io.TextIOWrapper'> Code language: Python (python)

Binary Files (BufferedReader and BufferedWriter)

Binary files store data as raw bytes. For example, images, videos, and executables are binary files. Their content is meant to be read by programs, not by people.

A program is needed to interpret the data in a binary file and display it to the user. In Python, binary file objects read and write bytes instead of strings, and they use a buffer to improve performance.

Open the binary files using the open() function in binary mode. For example, open('abc.txt', 'rb'). It opens the file to read-only in binary mode. The file pointer exists at the beginning of the file.

The open() function will return the BufferedReader when we open the binary file for reading and the BufferedWriter file object when we open a binary file for writing.

Example

file = open('test.txt', 'rb')
print(type(file))
# Output: <class '_io.BufferedReader'> Code language: Python (python)

Raw Files

A raw file object gives low-level access to the underlying file, without any buffering or text decoding.

Raw files are also called unbuffered files. Python reads and writes them directly, without a buffer, so every operation goes straight to the operating system. They are mainly used as a low-level building block for binary and text streams, and you rarely need them in everyday code.

When you open a file in binary mode with buffering=0, the open() function returns a FileIO object.

Example

file = open('test.txt', 'rb', buffering=0)
print(type(file))
# Output: <class '_io.FileIO'> Code language: Python (python)

File Object Attributes

A file object has the following attributes that you can use to access details of a file, such as its name and the mode in which it was opened.

  • name: Returns the name of the file, as passed to the open() function. It is a read-only attribute.
  • encoding: Returns the encoding used to convert between text and bytes, such as UTF-8. It is available only for text files. If you don’t pass an encoding to open(), Python uses the default encoding of your system.
  • mode: Returns the access mode used while opening the file.
  • closed: Returns True if the file is closed, and False otherwise.
  • newlines: In text mode, keeps track of the line endings found while reading the file. Its value is None (no line ending read yet), a string such as '\n' or '\r\n', or a tuple of all the line-ending types seen.

Example:

with open(r'E:\pynative\files\test.txt', 'r', encoding='utf-8') as fp:
    print('File Name:', fp.name)
    print('Is Closed:', fp.closed)
    print('Encoding Used:', fp.encoding)
    print('Access Mode:', fp.mode)
    print('NewLines Found:', fp.newlines)

# the with block has ended, so the file is closed
print('Is Closed:', fp.closed)Code language: Python (python)

Output:

File Name: E:\pynative\files\test.txt
Is Closed: False
Encoding Used: utf-8
Access Mode: r
NewLines Found: None
Is Closed: True

File Object Methods

A file object has the following methods that you can use to work with a file. Remember that you get a file object by calling the built-in open() function with the file’s path and an access mode.

Read More:

  • Open a file in Python
  • Create a file in Python
MethodDescription
read()Returns the file content.
readable()Returns whether the file stream can be read or not.
readline()Read single line
readlines()Read file into a list
truncate(size)Resizes the file to a specified size.
writable()Returns whether the file can be written to or not.
write()Writes the specified string to the file.
writelines()Writes a list of strings to the file.
close()Closes the opened file.
seek()Set file pointer position in a file
seekable()Returns whether the file allows us to change the file position.
tell()Returns the current file location.
detach()Returns the separated raw stream from the buffer
fileno()Returns a number that represents the stream, from the operating system’s perspective.
flush()Flushes the internal buffer.
isatty()Returns whether the file stream is interactive or not.
File Object Methods

Let’s see each method one by one.

read() Method

Syntax:

file_object.read(size)Code language: Python (python)
  • The size is the number of characters to read in text mode, or the number of bytes in binary mode. It returns the content as a string (text mode) or bytes (binary mode).
  • If size is negative or not specified, it reads all content until the end of the file (EOF).
  • An empty string is returned when the end of the file has already been reached.
  • When used in non-blocking mode, less data than requested may be returned.

Example:

# read(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
    # read 14 bytes
    # fp is file object
    print(fp.read(14))

    # read all remaining content
    print(fp.read())Code language: Python (python)

Output:

My First Line

My Second Line
My Third Line

Read More:

  • Complete Guide on Reading Files in Python
  • Read Specific Lines From a File in Python

readline() Method

Syntax:

file_object.readline(size)Code language: Python (python)
  • Reads one line from a file at a time and returns it as a string, including the trailing newline character.
  • If size is given, it reads at most that many characters from the line.
  • If the size argument is negative or not specified, it reads the whole line.
  • An empty string is returned when the end of the file (EOF) is reached.

Example:

# readline(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
    # read single line
    print(fp.readline())

    # read next line
    print(fp.readline())
Code language: Python (python)

Output:

My First Line

My Second Line

readlines() Method

Syntax:

file_object.readlines(size)Code language: Python (python)
  • Reads all lines from a file and returns them as a list of strings. Each string keeps its trailing newline character.
  • If the optional size hint is given, it stops reading once the total size of the lines read so far exceeds that value, instead of reading the entire file.

Example:

# readlines()
with open(r'E:\pynative\files\test.txt', 'r') as fp:
    # read all lines
    print(fp.readlines())Code language: Python (python)

Output:

['My First Line\n', 'My Second Line\n', 'My Third Line']

readable() Method

It checks whether the file stream can be read or not.

Example:

with open(r'E:\pynative\files\test.txt', 'r') as fp:
    # check if file object is readable
    print(fp.readable())
# Output TrueCode language: Python (python)

truncate(size) Method

Use the truncate() method to resize a file, for example, to remove its content after a certain position or to make it empty.

  • If the optional size argument is given, the file is cut down to (at most) that many bytes. For example, truncate(10) keeps the first ten bytes and removes everything after them.
  • If size is not given, it defaults to the current position of the file pointer. So, truncate(0) or calling truncate() at the beginning of the file makes the file empty.
  • The current file position is not changed.
  • If size is larger than the current file size, the result depends on the platform. Usually, the file is extended with zero bytes.
  • The file must be opened for writing, for example, in w, a, or r+ mode.

Example:

with open(r'E:\pynative\files\test.txt', 'r+') as fp:
    # keep only the first 5 bytes
    fp.truncate(5)
    print(fp.read())
# Output My FiCode language: Python (python)

write() Method

Write a string to the file. If buffering is used, the line may not show up in the file until the flush() or close() method is called.

Example:

with open(r'E:\pynative\files\test.txt', 'w') as fp:
    fp.write('My New Line')
Code language: Python (python)

Read More: Complete guide on write to file in Python

writelines() Method

  • Writes a list of strings to the file. Use it to write multiple lines at once. You can pass any iterable that produces strings, typically a list of strings.
  • Note: writelines() does not add line separators, so add \n to each string yourself.

Example:

with open(r'E:\pynative\files\test.txt', 'w') as fp:
    data = ['line1\n', 'line2\n', 'line3\n']
    fp.writelines(data)
Code language: Python (python)

writable() Method

It checks whether the file can be written to or not.

Example:

with open(r'E:\pynative\files\test.txt', 'w') as fp:
    # check if file object is writable
    print(fp.writable())
# Output True

with open(r'E:\pynative\files\test.txt', 'r') as fp:
    print(fp.writable())
# Output FalseCode language: Python (python)

close() Method

Close the opened file. A closed file cannot be read or written anymore. The ValueError will be raised if you try to read or write a closed file.

Example:

fp = open(r'E:\pynative\files\test.txt', 'r')
print(fp.read())
# close file
fp.close()Code language: Python (python)

Note: It is good practice to open a file using the with statement. It automatically closes the file and ensures that all the resources tied up with the file are released.

seek() and tell() Methods

The seek() function sets the position of a file pointer and the tell() function returns the current position of a file pointer.

Example:

with open(r'E:\pynative\files\test.txt', "r") as fp:
    # move the file pointer to the 6th position
    fp.seek(6)

    # get current position of the file pointer
    print(fp.tell())

    # read from the current position to the end
    print(fp.read())Code language: Python (python)

Output:

6
st Line
My Second Line
My Third Line

Read More: Complete Guide Python File Seek(): Move File Pointer Position

fileno() Method

Return the integer file descriptor used by the underlying implementation system to request I/O operations from the operating system. This can be useful for other lower-level interfaces that use file descriptors, such as os.read().

Example:

with open(r'E:\pynative\files\test.txt', "r") as fp:
    print(fp.fileno())
# Output 3Code language: Python (python)

flush() Method

As the name suggests, it flushes the internal buffer. Python collects written data in a buffer and writes it to the disk in larger chunks. Until you call flush() or close(), the data may not appear in the file. Call flush() when another program needs to see the data immediately, for example, in a log file.

Example:

with open(r'E:\pynative\files\test.txt', "w") as fp:
    fp.write('New Line')
    fp.flush()
Code language: Python (python)

isatty() Method

Returns True if the file is connected to an interactive terminal (TTY) device, such as a console window or a teleprinter, and False otherwise. It tells you whether the file stream is interactive. For example, sys.stdout.isatty() is usually True when you run a script in a terminal.

Example:

with open(r'E:\pynative\files\test.txt', "r") as fp:
    print(fp.isatty())
# Output FalseCode language: Python (python)

Iterate Over a File Object

A text file object is also an iterator. When you loop over it with a for loop, it returns one line at a time. This is the most memory-efficient way to process a large file, because the whole file is never loaded into memory.

with open(r'E:\pynative\files\test.txt', 'r') as fp:
    for line in fp:
        # strip() removes the trailing newline
        print(line.strip())Code language: Python (python)

Output:

My First Line
My Second Line
My Third Line

Summary

  • The open() function returns a file object. Its type depends on the mode: TextIOWrapper for text mode, BufferedReader or BufferedWriter for binary mode, and FileIO for unbuffered binary mode.
  • Attributes such as name, mode, closed, and encoding describe the file object.
  • Use read(), readline(), readlines(), or a for loop to read, and write() or writelines() to write.
  • Use seek() and tell() to move and find the file pointer, and flush() to force buffered data to disk.
  • Always close a file, preferably by opening it with the with statement.

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python File Handling

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python File Handling
TweetF  sharein  shareP  Pin

  Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com