Copy odd lines to another file

Copy odd lines to another file

EasyFile Handling Programs · 7 of 38

Write a Python program to copy the odd-numbered lines of a file to a separate file.

Output
one
three
five

Approach

  1. Read with line numbers and write the odd ones to a second file.

Solution

Python
with open("source.txt", "w") as f:    f.write("one\ntwo\nthree\nfour\nfive\n") with open("source.txt") as src, open("odd.txt", "w") as dst:    for i, line in enumerate(src, start=1):        if i % 2 == 1:            dst.write(line) print(open("odd.txt").read())
Output
one
three
five

Line by line

Line 4

One with statement can open two files.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Get a specific line

Get a specific line

EasyFile Handling Programs · 6 of 38

Write a Python program to get a specific line (by number) from a file.

Output
third None

Approach

  1. Loop with enumerate(f, start=1) and stop at the wanted line.

Solution

Python
with open("story.txt", "w") as f:    f.write("first\nsecond\nthird\nfourth\n") def get_line(path, number):    with open(path) as f:        for i, line in enumerate(f, start=1):            if i == number:                return line.rstrip("\n")    return None print(get_line("story.txt", 3), get_line("story.txt", 9))
Output
third None

Line by line

Lines 5-8

Reading line by line stops as soon as the line is found, even in a huge file.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Extract emails from a file

Extract emails from a file

EasyFile Handling Programs · 5 of 38

Write a Python program to get all email addresses from a text file.

Output
['asha@sqatools.in', 'ravi.k@gmail.com']

Approach

  1. Read the file and search it with a regular expression.

Solution

Python
import re with open("contacts.txt", "w") as f:    f.write("Asha asha@sqatools.in\nRavi ravi.k@gmail.com, phone 98765\nno email here\n") with open("contacts.txt") as f:    text = f.read()print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))
Output
['asha@sqatools.in', 'ravi.k@gmail.com']

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

First three and last three lines

First three and last three lines

EasyFile Handling Programs · 4 of 38

Write a Python program to get the first three and last three lines of a file.

Output
First: ['line 1', 'line 2', 'line 3']
Last: ['line 8', 'line 9', 'line 10']

Approach

  1. Read all lines into a list and slice it.

Solution

Python
with open("story.txt", "w") as f:    f.write("\n".join(f"line {i}" for i in range(1, 11)) + "\n") with open("story.txt") as f:    lines = f.read().splitlines()print("First:", lines[:3])print("Last:", lines[-3:])
Output
First: ['line 1', 'line 2', 'line 3']
Last: ['line 8', 'line 9', 'line 10']

Line by line

Line 5

splitlines() gives the lines without newline characters.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Append to a file

Append to a file

EasyFile Handling Programs · 3 of 38

Write a Python program to append data to an existing file.

Output
line 1
line 2
line 3

Approach

  1. Mode “a” writes at the end and keeps the existing content.

Solution

Python
with open("log.txt", "w") as f:    f.write("line 1\n") with open("log.txt", "a") as f:    f.write("line 2\n")    f.write("line 3\n") print(open("log.txt").read())
Output
line 1
line 2
line 3

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Overwrite a file

Overwrite a file

EasyFile Handling Programs · 2 of 38

Write a Python program to overwrite the content of an existing file.

Output
new content

Approach

  1. Opening in mode “w” empties the file before writing.

Solution

Python
with open("data.txt", "w") as f:    f.write("old content\n") with open("data.txt", "w") as f:    f.write("new content\n") print(open("data.txt").read())
Output
new content

Line by line

Lines 4-5

The second “w” open erased “old content” before writing.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Read a file in read mode

Read a file in read mode

EasyFile Handling Programs · 1 of 38

Write a Python program to read a file in reading mode.

Output
Python file handling
is easy with open()

Approach

  1. Create a sample file, then open it with mode “r” inside a with block and read it.

Solution

Python
with open("notes.txt", "w") as f:    f.write("Python file handling\nis easy with open()\n") with open("notes.txt", "r") as f:    content = f.read()print(content)
Output
Python file handling
is easy with open()

Line by line

Lines 1-2

Creates the sample file so the program runs anywhere.

Line 4

Mode “r” (the default) opens the file for reading; with closes it automatically.

Line 5

read() returns the whole file as one string.

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs

Python File Handling Programs with Solutions

Python Practice › File Handling Programs

Python File Handling Programs with Solutions

38 programs38 easy0 medium0 hard

38 file handling programs: reading, writing and appending, working line by line, counting words and characters, copying with changes, and moving the cursor. Every solution first creates its own sample file, so you can run it anywhere, including with the Try it button.

Before you start

Read the File Handling and Read/Write JSON and Read/Write CSV lesson first if the topic is new to you.

All programs

Read File In Python

Method read() reads at most size bytes from the file and read hits the end of the file before obtaining size bytes, then it reads only available bytes.

read_file.txt input file

input file.txt
In the below program example, we are opening a text file with read mode, and read mode has this read method that read the entire file content from beginning to end. The open method accepts two parameters file path and file mode to open.
def read_file_content(filename):
    file = open(filename, 'r+')
    file_data = file.read()
    print(file_data)

filename = "input_file.txt"
read_file_content(filename)

Output:

output data