Copy a file in lowercase

Copy a file in lowercase

EasyFile Handling Programs · 12 of 38

Write a Python program to copy a file’s contents to another file in lowercase.

Output
hello world
python files

Approach

  1. Read, lower(), write.

Solution

Python
with open("in.txt", "w") as f:    f.write("Hello World\nPYTHON Files\n") with open("in.txt") as src, open("lower.txt", "w") as dst:    dst.write(src.read().lower())print(open("lower.txt").read())
Output
hello world
python files

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Random line from a file

Random line from a file

EasyFile Handling Programs · 11 of 38

Write a Python program to read a random line from a file.

Output
Test early

Approach

  1. Read the lines and use random.choice; seed for a repeatable demo.

Solution

Python
import random with open("quotes.txt", "w") as f:    f.write("Keep it simple\nTest early\nAutomate the boring stuff\nRead the error\n") random.seed(4)with open("quotes.txt") as f:    lines = f.read().splitlines()print(random.choice(lines))
Output
Test early

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Count a word in a file

Count a word in a file

EasyFile Handling Programs · 10 of 38

Write a Python program to count how many times a word occurs in a file.

Output
4

Approach

  1. Lower-case the words and count matches.

Solution

Python
with open("story.txt", "w") as f:    f.write("Test early. Test often.\nA good test is a fast test.\n") with open("story.txt") as f:    words = [w.strip(".,").lower() for w in f.read().split()]print(words.count("test"))
Output
4

Line by line

Line 5

Stripping punctuation and lower-casing makes “Test”, “test.” and “test” match.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Longest word in a file

Longest word in a file

EasyFile Handling Programs · 9 of 38

Write a Python program to find the longest word in a file.

Output
experimentation

Approach

  1. Split the text into words and use max(key=len).

Solution

Python
with open("story.txt", "w") as f:    f.write("Python makes automation\nand experimentation enjoyable\n") with open("story.txt") as f:    words = f.read().split()print(max(words, key=len))
Output
experimentation

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Read lines into a list

Read lines into a list

EasyFile Handling Programs · 8 of 38

Write a Python program to read a file line by line into a list.

Output
['pen\n', 'book\n', 'bag\n']
['pen', 'book', 'bag']

Approach

  1. readlines() keeps “\n”; read().splitlines() removes it.

Solution

Python
with open("items.txt", "w") as f:    f.write("pen\nbook\nbag\n") with open("items.txt") as f:    print(f.readlines())with open("items.txt") as f:    print([line.rstrip("\n") for line in f])
Output
['pen\n', 'book\n', 'bag\n']
['pen', 'book', 'bag']

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

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