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.

Advertisement
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

Leave a Comment