PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

File Handling in Python

← All stacks

Theory

67/268

File Handling in Python

File handling is reading and writing disk files. open(path, mode) with "r" read, "w" write (erases existing), "a" append, "rb" binary. Prefer with open(...) as f: so the file closes even if an error happens. read(), readline(), readlines() for input. write() / writelines() for output.

Trap: "w" on a marks file you meant to read — content gone. Always mention with in the viva. Then one tiny write of "Asha,90\n" and read it back.

File Handling in Python — output: Asha then Pune. StringIO is the same read pattern as a real file, and this script always runs.

Diagram
with open(...) as f
         │ read / write
         ▼
      auto close
Exam tip

with open as best practice.

Example

# File idea
from io import StringIO
f = StringIO("Asha\nPune")
print(f.readline().strip())
print(f.readline().strip())

File Handling in Python — output: Asha then Pune. StringIO is the same read pattern as a real file, and this script always runs.

Short notes

  • Defopen + modes. with auto-close.
  • Rule"w" overwrites.
  • Rememberread / write helpers.

Questions

1

Explain File Handling as if you are teaching a junior — definition, then one tiny script.

2

What does the example print, and why?

3

What mistake do freshers make with File Handling?

Previous← Built-in exceptionsNextRead CSV File in Python →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.