Signup/Sign In

File handling in Python

Posted in Programming   LAST UPDATED: DECEMBER 11, 2019

    Python has a plethora of built-in packages and modules that help manage and handle files. A few of the modules include os, os.shutil, and os.path. We will look at a few operations in this article which can be performed using the 'with open as' pattern to handle files in python.


    1. Python: To write to a file

    The below example demonstrates how a text file can be opened in the append mode to keep adding data from a data source named data. The writelines method writes the list of data into a specific path. Opening the file in append mode indicates that the stream of data is inserted starting from the current position (after the existing content of the file) and this goes on until the end of the file is encountered.


    Time for an example:

    data = "path to data file"
    filepath = "path to text file"
    
    with open(filepath, 'a+') as infile:
        infile.writelines(data)    

    Output:

    A file (if not present) is created in the 'filepath' location. Into this file, the contents of 'data' are appended. 



    2. To read from a file and display it on the console

    The below code opens a file in the read mode and reads the stream of data. It stores the data which is read into a variable called data. We can then print the content of the file on the console.


    Time for an example:

    filepath = "path to file that needs to be read"
    with open(filepath, 'r') as infile:
        data = infile.read()
        print(data)

    Output:

    Contents of the filepath are displayed



    3. Finding all the files of a specific directory using 'os' module

    The os module, which is built-in, provides a wide variety of methods that would list all the files present in a specific directory. Python version 2.x uses os.listdir() method and Python 3.x version uses os.scandir. But os.listdir can be used with Python 3.x as well.


    3.1 Using os.listdir() function

    In the code example below, we have used the os.listdir() function to print the names of all the files present in a directory.

    import os
    
    for file in os.listdir("path to directory"):
        print(file)

    Output:

    All the files present in that directory. (These entries are of the type 'str')

    3.2 Using os.scandir() function

    In the code example below, we have used the os.scandir() function to print the names of all the files present in a directory.

    import os
    
    for file in os.scandir("path to directory"):
        print(type(file))    


    Output:

    All files present in the specific directory. (It is of the type <class 'nt.DirEntry'>)
    



    4. Finding a specific type of file (with a specific extension) present in a directory

    In the code below we will be using the os.listdir() function to find and print the names of files with a given extension.

    import os
    
    for file in os.listdir("path to directory"):
        if file.endswith(".txt"):
            print(os.path.join("", file))

    Output:

    Returns all files which have extension '.txt'.



    Conclusion

    In this post, we saw how a file can be opened to read and write in different modes. We also saw how the files of a specific directory can be listed with the help of certain os methods.

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:PythonPython File handlingFile Handling
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS