Skip to contentSkip to navigation

Module 2 of 6, Practical Python

Files and Data Formats

Read and write files, work with paths, and load and save JSON and CSV data.

module checksSign in to track

  • Lessons complete-, not done
  • Lesson quizzes taken-, not done
  • Module Labs passed-, not done
  • Module exam passed at 80%-, not done
lessons
4
quiz questions
48
reading time
33 min
exam length
15 Q
coding exercises
7

Lessons

  1. Reading and Writing Text FilesKeep data after a program ends: open text files with the right mode, read them whole or line by line, write and append safely, and let with close the file for you. 9 min 12 questions
  2. Paths and Folders with pathlibWork with files and folders through Path objects: build paths with /, read their parts, check what exists, create folders, list and search them, and read or write a file in one call. 8 min 12 questions
  3. JSON Files and DataSave and load whole lists and dictionaries as JSON: convert with dumps and loads, read and write files with dump and load, format the output, and know which Python values change on the way. 8 min 12 questions
  4. CSV Files: Reading and Writing TablesHandle spreadsheet-style data: read CSV rows with csv.reader and DictReader, convert their text to numbers, and write tables back out with csv.writer and DictWriter. 8 min 12 questions

Lab: write it yourself

Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (3 exercises)

All module exercises

The Lab needs an account. Sign in or create a free ID to run these exercises.

Lab 1: Path stem extraction

Sign-in required

Construct a pathlib.Path("data/reports/q3_earnings.xlsx"). Extract and print its stem and suffix: Stem: q3_earnings, Suffix: .xlsx.

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

Lab 2: CSV salary sum

Sign-in required

Parse CSV text "name,pay\nAli,500\nSara,700" using csv.DictReader and io.StringIO. Print: Total payroll: 1200.

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

Lab 3: Serialize JSON

Sign-in required

Serialize {"status": "healthy", "uptime": 99.9} to a JSON string with indent=2 and print it.

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

References & Further Reading

Related entries from PyLabs's own reference library.

  • open() (Open a file so you can read from it or write to it.)
  • read() (Read at most size characters or bytes from the file.)
  • write() (Write a string or bytes to the file stream.)