Is a file closed?

Is a file closed?

EasyFile Handling Programs · 23 of 38

Write a Python program to check whether a file is closed.

Output
False
True
inside with: False
after with: True

Approach

  1. The closed attribute.

Solution

Python
f = open("temp.txt", "w")print(f.closed)f.close()print(f.closed) with open("temp.txt") as g:    print("inside with:", g.closed)print("after with:", g.closed)
Output
False
True
inside with: False
after with: True

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Write a tuple to a file

Write a tuple to a file

EasyFile Handling Programs · 22 of 38

Write a Python program to write a tuple to a file and read it back.

Output
(12, 45, 78) True

Approach

  1. Write one item per line; convert back when reading.

Solution

Python
data = (12, 45, 78)with open("tuple.txt", "w") as f:    f.write("\n".join(map(str, data))) with open("tuple.txt") as f:    loaded = tuple(int(line) for line in f)print(loaded, loaded == data)
Output
(12, 45, 78) True

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Size of a file

Size of a file

EasyFile Handling Programs · 21 of 38

Write a Python program to get the size of a file in bytes.

Output
1500 bytes

Approach

  1. os.path.getsize().

Solution

Python
import os with open("data.bin", "wb") as f:    f.write(b"x" * 1500) print(os.path.getsize("data.bin"), "bytes")
Output
1500 bytes

Line by line

Line 3

Writing in binary mode makes the size exact on every operating system.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Count lines in a file

Count lines in a file

EasyFile Handling Programs · 20 of 38

Write a Python program to count the lines in a file.

Output
4

Approach

  1. sum(1 for _ in f) counts without storing the lines.

Solution

Python
with open("story.txt", "w") as f:    f.write("a\nb\nc\nd\n") with open("story.txt") as f:    print(sum(1 for _ in f))
Output
4

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

Compare two files

Compare two files

EasyFile Handling Programs · 19 of 38

Write a Python program to compare two files and show the lines that differ.

Output
Same: False
--- a.txt
+++ b.txt
@@ -2 +2 @@
-line two
+line 2

Approach

  1. filecmp.cmp for equal/not equal; difflib to show differences.

Solution

Python
import difflibimport filecmp with open("a.txt", "w") as f:    f.write("line one\nline two\nline three\n")with open("b.txt", "w") as f:    f.write("line one\nline 2\nline three\n") print("Same:", filecmp.cmp("a.txt", "b.txt", shallow=False))with open("a.txt") as a, open("b.txt") as b:    for line in difflib.unified_diff(a.readlines(), b.readlines(), "a.txt", "b.txt", n=0):        print(line.rstrip("\n"))
Output
Same: False
--- a.txt
+++ b.txt
@@ -2 +2 @@
-line two
+line 2

Line by line

Line 9

shallow=False compares the contents, not just size and date.

Line 11

A unified diff shows removed lines with - and added lines with +.

Learn the concept

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

More file handling programs

← All 38 File Handling Programs

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