File Read Write Operation in Python

This article will discuss Python file handling like file open, read, write, append and binary. File handling will have different modes ('r,' 'w,' 'a', 'b'). In Python, the reading file will have three functions: read, readline, and deadlines.

  • read: read all content of the file
  • deadline: read the next line of the file 
  • readlines: read all lines and return to the list

Sample input File

Mistakes are like little bumps in the road of life.
They might make you stumble
but they also teach you how to do things better next time.

Code Example 

def read_file(file_name):
    with open(file_name, 'r') as file:
        data = file.read()
        print(data)
        return data
  
def read_file_into_list(file_name): 
    with open(file_name, 'r') as file:
        data = file.readlines()
        return data

Output

Mistakes are like little bumps in the road of life.
They might make you stumble
but they also teach you how to do things better next time.
['Mistakes are like little bumps in the road of life.\n', 'They might make you stumble\n', 'but they also teach you how to do things better next time.']

Will see the even number lines appending and return the file line in reverse order example. Code example below

Code Example 


def read_even_numbered_lines(file_name):   
    with open(file_name, 'r') as file:
        content = file.readlines()
        data = []
        for x in range(len(content)):
            if x % 2 != 0:
                data.append(content[x])
                print("Even number reading")
        return data

def read_file_in_reverse(file_name):
    with open(file_name, 'r') as file:
        data = []
        content = file.readlines()
        for x in range(len(content) - 1, -1, -1):
            data.append(content[x])
        print("Reverse order")
        return data
print(read_even_numbered_lines("sampletext.txt"))
print(read_file_in_reverse("sampletext.txt"))

Output

Even number reading
['They might make you stumble\n']
Reverse order
['but they also teach you how to do things better next time.', 'They might make you stumble\n', 'Mistakes are like little bumps in the road of life.\n'] 

Write a function to read the file content and write the first line only in new files.

Code Example 

def write_first_line_to_file(file_contents, output_filename):    
    data = file_contents.split('\n')
    with open(output_filename, 'w') as file:
        file.write(data[0])

 Output

Mistakes are like little bumps in the road of life.


Recommended Free Ebook
Similar Articles