HelpContactFor teachers and institutes
>_StemPy Lab
Mock TestsClasses

>_StemPy Lab

Learn. Solve. Code the solutions. Test yourself.

Live examsFree mock exams, timed and rankedEveryone starts together, and your score and rank come the moment it ends.See the exams →
Live examsInternational live exams are comingTell us which exam you want first. Timed practice papers are open now.See what is coming →

Learn

  • Physics
  • Chemistry
  • Mathematics
  • Biology
  • Python Programming
  • Statistics & Data Science
  • Computer Science
  • Space Science and Astronomy
  • Earth and Environmental Science
  • Classes
  • Groups

Practice

  • Problems
  • Quizzes
  • Mock Tests
  • Prepare for an Exam
  • Question Sets
  • Exams
  • Certificates
  • Python Labs
  • AI Practice Generator
  • Student-Created Tests

Community

  • Discussions
  • Resources
  • Notes
  • Glossary
  • Blog

Account

  • Log in
© 2026 senLearn. All rights reserved.HelpFor SchoolsAboutContactPrivacy PolicyTerms of UseRefund Policy
  1. Python Programming
  2. /Python Going Further
  3. /Files and Data Formats

Files and Data Formats

Python Programming · High School (11–12) · 1 course, 11 worked problems, 28 practice questions

A program loses its variables when it stops, so data that must be kept goes into files. In Python you open a file with open(), usually inside a with block so that it closes safely. You can read it line by line, write to it, or append new lines. Many files follow a standard format. A CSV file stores a table as lines of values separated by commas, and the csv module reads it. A JSON file stores nested data, such as dictionaries and lists, and the json module turns it into Python objects. These formats let programs share data.

With practice you will be able to

  • Read and write a text file with open() and with
  • Read rows from a CSV file and work with the values
  • Save a dictionary to a JSON file and load it back

On the syllabus of

  • CBSE / State Class 12
  • Python Certification
  • A-Level
  • IGCSE

Lessons

  • Files and Data FormatsCan opening a file wipe it out? How does a program remember between runs?High School (11–12)

Practice questions

Choose an answer, then check it. Each one shows a full explanation.

A program writes to a file inside a with block, then uses the file object after the block. with open("a.txt", "w") as f: print(f.closed, end=" ") f.write("hi") print(f.closed, f.name) f.write("again") What happens when the program runs?

A class adds lines to a text file, and reads the file back. The folder has no file log.txt at the start. class Log: def __init__(self, path): self.path = path def add(self, text): with open(self.path, "a") as f: f.write(text + "\n") def lines(self): with open(self.path) as f: return f.read().split("\n") log = Log("log.txt") log.add("start") log.add("stop") print(log.lines()) What does the program print?

A program writes three bytes to a binary file, then reads them into a bytearray. data = bytearray(b"ABCDEF") with open("bin.dat", "wb") as f: f.write(data[1:4]) buf = bytearray(5) with open("bin.dat", "rb") as f: n = f.readinto(buf) print(n, buf[:n].decode(), buf[3], len(buf)) What does the program print?

A program writes to a new file with write and with print, then reads the whole file back. It prints nothing on the screen. with open("out.txt", "w") as f: n = f.write("ab\n") print("cd", "ef", sep="-", file=f) with open("out.txt") as f: text = f.read() Which of these give True after the code? Choose every correct option.

One or more options are correct. Tick all the correct ones: a wrong option costs marks, and a part-right answer earns part of the marks.

The file words.txt holds three lines, red, green and blue, each with a new line at its end. A program reads part of it with read, then loops over the rest. with open("words.txt") as f: start = f.read(5) for line in f: print(line.strip().upper(), end=" ") print(repr(start)) What does the program print?

A program writes three lines to a file, then adds up the lines that are numbers. A line that is not a number counts as 100. with open("n.txt", "w") as f: f.write("3\nx\n5\n") total = 0 with open("n.txt") as f: for row in f: try: total += int(row) except ValueError: total += 100 print(total, f.closed) What does the program print?

A program writes a file in two steps, then reads it back. with open("log.txt", "w") as f: f.write("one\ntwo\n") with open("log.txt", "a") as f: f.write("three") with open("log.txt") as f: first = f.readline() rest = f.readlines() print(repr(first), rest, len(rest)) What does the program print?

A folder holds a file notes.txt with the text hi. It has no file new.txt. Each line below is run on its own, in a fresh copy of the folder. Which lines run without raising an exception? Choose every correct option.

One or more options are correct. Tick all the correct ones: a wrong option costs marks, and a part-right answer earns part of the marks.

A program opens notes.txt in mode "w" and calls f.write("hi\n") three times. How many lines does the file have?

What is "Asha:72".split(":")[1], and what type is it?

All 28 practice questions on Files and Data Formats →

Worked problems

Each one has a hint, the key idea and a full worked solution.

  • A file visits.txt is made with "w", and the line Asha is written…Easy
  • Write a function read_number(name) that reads a file with one whole number in it, and gives the…Medium
  • A file nums.txt has one number on each line: 4, 9, 2, 7…Easy
  • Make a file poem.txt with the three lines roses are red, violets are blue and sugar is sweet…Medium
  • Write a function longest_line(name) that gives the longest line of a file, without its new line…Easy
  • A file marks.txt holds Asha:72, Ravi:85, Meera:64, one on each line…Medium
  • A CSV text has the header item,price,quantity and the rows pen,10,3, book,80,1 and bag,450,2…Medium
  • Write a CSV file scores.csv with the header name,score and the rows Asha,72 and Rao, Ravi,85 (the…Easy
  • For data = {"p": (1, 2), 3: "x", "t": {"a"}}, say what json.dumps(data) does, and what you must…Medium
  • Write load_list(name) that gives the list that is saved in a JSON file…Medium
  • A to-do list is kept in a JSON file as a list of texts…Medium

Python labs

  • Write and read lines
  • Read the marks file
  • Parse CSV text
  • JSON round trip
  • Project: a marks book that remembers

Related topics

  • Python Going Further
  • Classes and Objects
  • Inheritance and Special Methods
  • Comprehensions, Iterators and Generators
  • Data Structures
  • Testing and Debugging