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

File Objects in Python

Last Updated : 03 Apr, 2017
Improve
Improve
Like Article
Like
Save
Share
Report

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.




    <div id="highlighter_373886" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="comments"># Writing a file </code></div><div class="line number2 index1 alt1"><code class="plain">f </code><code class="keyword">=</code> <code class="functions">open</code><code class="plain">(__file__, </code><code class="string">'a+'</code><code class="plain">) </code></div><div class="line number3 index2 alt2"><code class="plain">lines </code><code class="keyword">=</code> <code class="plain">f.readlines() </code></div><div class="line number4 index3 alt1"><code class="undefined spaces"> </code> </div><div class="line number5 index4 alt2"><code class="comments">#writelines() </code></div><div class="line number6 index5 alt1"><code class="plain">f.writelines(lines) </code></div><div class="line number7 index6 alt2"><code class="plain">f.close() </code></div></div></td></tr></tbody></table></div>

    
    

  • 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.




    # Appending and reading a file
    f = open(__file__, 'a+')
    lines = f.read()
    f.write(lines)
    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.




    # Writing a file
    f = open(__file__, 'a+')
    lines = f.readlines()
      
    #writelines()
    f.writelines(lines)
    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.




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

    
    

    More Examples in different modes:




    # 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()

    
    




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

    
    




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

    
    




    # Checks if file is connected to a tty(-like) device
    f = open(__file__, 'r')
      
    #isatty()
    print(f.isatty())
    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.




    # Iterates over the file
    f = open(__file__, 'r')
      
    #next()
    try:
        while f.next():
            print(f.next())
    except:
        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




    # Truncates the file
    f = open(__file__, 'w')
      
    #truncate()
    f.truncate(10)
    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.




    # Opening and closing a file
    f = open(__file__, 'r')
      
    #close()
    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.




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

    
    

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




    
    

  • 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
Extract Multiple JSON Objects from one File using Python
Python is extremely useful for working with JSON( JavaScript Object Notation) data, which is a most used format for storing and exchanging information. However, it can become challenging when dealing with multiple JSON objects stored within a single file. In this article, we will see some techniques to easily extract multiple JSON Objects from a fi
3 min read
reStructuredText | .rst file to HTML file using Python for Documentations
Introduction to .rst file (reStructuredText): reStructuredText is a file format for Textual data majorly used by Python based communities to develop documentation in an easy way similar to other tools like Javadoc for Java. Most of the docs of Python-based software and libraries are written using reStructuredText and hence it's important to learn i
2 min read
Python - Copy contents of one file to another file
Given two text files, the task is to write a Python program to copy contents of the first file into the second file. The text files which are going to be used are second.txt and first.txt: Method #1: Using File handling to read and append We will open first.txt in 'r' mode and will read the contents of first.txt. After that, we will open second.txt
2 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
Create a GUI to convert CSV file into excel file using Python
Prerequisites: Python GUI – tkinter, Read csv using pandas CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma. Modules Needed Pandas: Python i
3 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
Article Tags :
Practice Tags :