The Wayback Machine - https://web.archive.org/web/20240824184835/https://www.geeksforgeeks.org/file-objects-python/
Open In App

File Objects in Python

Last Updated : 03 Apr, 2017
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A file object allows us to use, access and manipulate all the user accessible files. One can read and write any such files.
When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.
Files have the following methods:

  • open(): Opens a file in given access mode.
     open(file_address, access_mode) 

    Examples of accessing a file: A file can be opened with a built-in function called open(). This function takes in the file’s address and the access_mode and returns a file object.
    There are different types of access_modes:

    r: Opens a file for reading only
    r+: Opens a file for both reading and writing
    w: Opens a file for writing only
    w+: Open a file for writing and reading.
    a: Opens a file for appending
    a+: Opens a file for both appending and reading

    When you add 'b' to the access modes you can read the file in binary format rather than the default text format. It is used when the file to be accessed is not in text.

  • read([size]): It reads the entire file and returns it contents in the form of a string. Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached.




    # Reading a file
    f = open(__file__, 'r')
      
    #read()
    text = f.read(10)
      
    print(text)
    f.close()

    
    

  • readline([size]): It reads the first line of the file i.e till a newline character or an EOF in case of a file having a single line and returns a string. If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.




    # Reading a line in a file
    f = open(__file__, 'r')
      
    #readline()
    text = f.readline(20)
    print(text)
    f.close()

    
    

  • readlines([sizehint]): It reads the entire file line by line and updates each line to a list which is returned.Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read.




    # Reading a file
    f = open(__file__, 'r')
      
    #readline()
    text = f.readlines(25)
    print(text)
    f.close()

    
    

  • write(string): It writes the contents of string to the file. It has no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.




    # Writing a file
    f = open(__file__, 'w')
    line = 'Welcome Geeks\n'
      
    #write()
    f.write(line)
    f.close()

    
    

    More Examples in different modes:




    # Reading and Writing a file
    f = open(__file__, 'r+')
    lines = f.read()
    f.write(lines)
    f.close()

    
    




    # Writing and Reading a file
    f = open(__file__, 'w+')
    lines = f.read()
    f.write(lines)
    f.close()

    
    




    # Appending a file
    f = open(__file__, 'a')
    lines = 'Welcome Geeks\n'
    f.write(lines)
    f.close()

    
    




    # Appending and reading a file
    f = open(__file__, 'a+')
    lines = f.read()
    f.write(lines)
    f.close()

    
    

  • writelines(sequence): It is a sequence of strings to the file usually a list of strings or any other iterable data type. It has no return value.




    # Writing a file
    f = open(__file__, 'a+')
    lines = f.readlines()
      
    #writelines()
    f.writelines(lines)
    f.close()

    
    

  • tell(): It returns an integer that tells us the file object’s position from the beginning of the file in the form of bytes




    # Telling the file object position
    f = open(__file__, 'r')
    lines = f.read(10)
      
    #tell()
    print(f.tell())
    f.close()

    
    

  • seek(offset, from_where): It is used to change the file object’s position. Offset indicates the number of bytes to be moved. from_where indicates from where the bytes are to be moved.




    # Setting the file object position
    f = open(__file__, 'r')
    lines = f.read(10)
    print(lines)
      
    #seek()
    print(f.seek(2,2))
    lines = f.read(10)
    print(lines)
    f.close()

    
    

  • flush(): Flush the internal buffer, like stdio‘s fflush(). It has no return value. close() automatically flushes the data but if you want to flush the data before closing the file then you can use this method.




    # Clearing the internal buffer before closing the file
    f = open(__file__, 'r')
    lines = f.read(10)
      
    #flush()
    f.flush()
    print(f.read())
    f.close()

    
    

  • fileno(): Returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.




    # Getting the integer file descriptor
    f = open(__file__, 'r')
      
    #fileno()
    print(f.fileno())
    f.close()

    
    

  • isatty(): Returns True if the file is connected to a tty(-like) device and False if not.




    # Checks if file is connected to a tty(-like) device
    f = open(__file__, 'r')
      
    #isatty()
    print(f.isatty())
    f.close()

    
    

  • next(): It is used when a file is used as an iterator. The method is called repeatedly. This method returns the next input line or raises StopIteration at EOF when the file is open for reading( behaviour is undefined when opened for writing).




    # Iterates over the file
    f = open(__file__, 'r')
      
    #next()
    try:
        while f.next():
            print(f.next())
    except:
        f.close()

    
    

  • truncate([size]): Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content.




    # Truncates the file
    f = open(__file__, 'w')
      
    #truncate()
    f.truncate(10)
    f.close()

    
    

  • close(): Used to close an open file. A closed file cannot be read or written any more.




    # Opening and closing a file
    f = open(__file__, 'r')
      
    #close()
    f.close()

    
    

  • Attributes:
    • closed: returns a boolean indicating the current state of the file object. It returns true if the file is closed and false when the file is open.
    • encoding: The encoding that this file uses. When Unicode strings are written to a file, they will be converted to byte strings using this encoding.
    • mode: The I/O mode for the file. If the file was created using the open() built-in function, this will be the value of the mode parameter.
    • name: If the file object was created using open(), the name of the file.
    • newlines: A file object that has been opened in universal newline mode have this attribute which reflects the newline convention used in the file. The value for this attribute are “\r”, “\n”, “\r\n”, None or a tuple containing all the newline types seen.
    • softspace: It is a boolean that indicates whether a space character needs to be printed before another value when using the print statement.




      f = open(__file__, 'a+')
      print(f.closed)
      print(f.encoding)
      print(f.mode)
      print(f.newlines)
      print(f.softspace)

      
      

Related Article :
Reading and Writing to text files in Python

Reference: https://docs.python.org/2.4/lib/bltin-file-objects.html



Similar Reads

Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python program to reverse the content of a file and store it in another file
Given a text file. The task is to reverse as well as stores the content from an input file to an output file. This reversing can be performed in two types. Full reversing: In this type of reversing all the content gets reversed. Word to word reversing: In this kind of reversing the last word comes first and the first word goes to the last position.
2 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
Python - Copy all the content of one file to another file in uppercase
In this article, we are going to write a Python program to copy all the content of one file to another file in uppercase. In order to solve this problem, let's see the definition of some important functions which will be used: open() - It is used to open a file in various modes like reading, write, append, both read and write.write() - It is used t
2 min read
How to convert a PDF file to TIFF file using Python?
This article will discover how to transform a PDF (Portable Document Format) file on your local drive into a TIFF (Tag Image File Format) file at the specified location. We'll employ Python's Aspose-Words package for this task. The aspose-words library will be used to convert a PDF file to a TIFF file. Aspose-Words: Aspose-Words for Python is a pot
3 min read
MoviePy – Getting Original File Name of Video File Clip
In this article we will see how we can get the original file name of the video file in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Original file name is the name of the original video that existed in the first place i.e which was loaded, even after altering and editing of the vi
2 min read
PYGLET – Opening file using File Location
In this article we will see how we can open a file using file location object in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set t
3 min read
PyCairo - Saving SVG Image file to PNG file
In this article, we will see how we can save an SVG file to a PNG file using PyCairo in Python. We can create an SVG file using SVGSurface method. An SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files ar
2 min read
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
How to get Scrapy Output File in XML File?
Prerequisite: Implementing Web Scraping in Python with Scrapy Scrapy provides a fast and efficient method to scrape a website. Web Scraping is used to extract the data from websites. In Scrapy we create a spider and then use it to crawl a website. In this article, we are going to extract population by country data from worldometers website. Let's i
2 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python | Unit Test Objects Patching | Set-1
The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual
2 min read
Python | Unit Test Objects Patching | Set-2
MagicMock instances that are normally used as replacement values are meant to mimic callables and instances. They record information about usage and allow to make assertions as shown in the code given below - Code #6: from unittest.mock import MagicMock m = MagicMock(return_value = 10) print(m(1, 2, debug = True), "\n") m.assert_called_wi
2 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
2 min read
Print objects of a class in Python
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
2 min read
Python: Difference between Lock and Rlock objects
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is si
5 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Session Objects - Python requests
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.
2 min read
Built-in Objects in Python-builtins
This Python module provides direct access to all 'built-in' identifiers of Python. For example, builtins.open is the full name for the built-in function open(). This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of
3 min read
Encoding and Decoding Custom Objects in Python-JSON
JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
5 min read
Detecting objects of similar color in Python using OpenCV
OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar. Libraries needed:OpenCV NumpyApproach: First of all, we need to read the image which is
3 min read
Addition and Subtraction on TimeDelta objects using Pandas - Python
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series - 1) Addition - df['Result'] = df['TimeDelta1']
2 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
Access object within another objects in Python
Prerequisite: Basics of OOPs in Python In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects w
2 min read
Article Tags :
Practice Tags :