Mobile numbers from a file

Mobile numbers from a file

EasyFile Handling Programs · 18 of 38

Write a Python program to get all 10-digit mobile numbers from a file.

Output
['9876543210', '9123456780']

Approach

  1. re.findall(r"\b\d{10}\b", text).

Solution

Python
import re with open("contacts.txt", "w") as f:    f.write("Asha 9876543210\nRavi 12345\nMeena 9123456780 and 99887766554\n") with open("contacts.txt") as f:    print(re.findall(r"\b\d{10}\b", f.read()))
Output
['9876543210', '9123456780']

Line by line

Line 7

The 11-digit number does not match because \b requires the digits to end there.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Odd and even length words

Odd and even length words

EasyFile Handling Programs · 17 of 38

Write a Python program to put the words of a file into two lists by odd and even length.

Output
Even: ['Python', 'make', 'simple']
Odd: ['files', 'testing']

Approach

  1. Test len(word) % 2.

Solution

Python
with open("story.txt", "w") as f:    f.write("Python files make testing simple\n") with open("story.txt") as f:    words = f.read().split()print("Even:", [w for w in words if len(w) % 2 == 0])print("Odd:", [w for w in words if len(w) % 2 == 1])
Output
Even: ['Python', 'make', 'simple']
Odd: ['files', 'testing']

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Create A.txt to Z.txt

Create A.txt to Z.txt

EasyFile Handling Programs · 16 of 38

Write a Python program to create text files named A.txt to Z.txt.

Output
26 ['A.txt', 'B.txt', 'C.txt'] Z.txt

Approach

  1. Loop over string.ascii_uppercase and create each file in a folder.

Solution

Python
import osimport string os.makedirs("letters", exist_ok=True)for letter in string.ascii_uppercase:    with open(os.path.join("letters", f"{letter}.txt"), "w") as f:        f.write(f"This is file {letter}\n") files = sorted(os.listdir("letters"))print(len(files), files[:3], files[-1])
Output
26 ['A.txt', 'B.txt', 'C.txt'] Z.txt

Line by line

Line 4

The files go into a separate folder to keep things tidy.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Count all words in a file

Count all words in a file

EasyFile Handling Programs · 14 of 38

Write a Python program to count all the words in a file.

Output
8

Approach

  1. Sum the word count of each line.

Solution

Python
with open("story.txt", "w") as f:    f.write("Python is fun\nFiles are easy to read\n") with open("story.txt") as f:    print(sum(len(line.split()) for line in f))
Output
8

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Copy a file in uppercase

Copy a file in uppercase

EasyFile Handling Programs · 13 of 38

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

Output
HELLO WORLD
PYTHON FILES

Approach

  1. Process line by line so large files work too.

Solution

Python
with open("in.txt", "w") as f:    f.write("Hello World\nPython Files\n") with open("in.txt") as src, open("upper.txt", "w") as dst:    for line in src:        dst.write(line.upper())print(open("upper.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

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