Computer ScienceClass 12File Handling in Python

File Handling in Python: A Complete Guide for Class 12 NCERT Students

By ConceptScroll Team · Published on 2 July 2026 · 5 min read

File Handling in Python: A Complete Guide for Class 12 NCERT Students

File Handling in Python is essential for Class 12 NCERT Computer Science students to manage data storage efficiently. This guide explains how to open, read, write, and close files with clear examples and best practices.

Understanding File Handling in Python: Basics and Importance

File Handling in Python lets you store and retrieve data from permanent storage devices like hard drives or USBs. In Class 12 NCERT Computer Science, mastering this topic is vital because it forms the foundation for data processing and management.

A file is a collection of bytes stored on a storage device. Python provides built-in functions to open, read, write, and close files easily. The basic syntax to open a file is:

``python f = open('filename.txt', 'mode') ``

Here, 'mode' specifies how you want to interact with the file. Common modes include:

  • 'r': Read mode (default) – opens file for reading
  • 'w': Write mode – opens file for writing (overwrites existing content)
  • 'a': Append mode – opens file to add content at the end
  • 'r+': Read and write mode

Understanding these modes helps you choose the right way to handle files depending on your program's needs.

How to Read Files in Python: Methods and Examples

Reading data from files is a common task in Python. The NCERT Class 12 syllabus focuses on three main methods to read files:

1. read()

  • Reads the entire file or a specified number of bytes.
  • Example:

``python f = open('data.txt', 'r') content = f.read() # reads whole file print(content) f.close() ``

2. readline()

  • Reads one line at a time, useful for processing line-by-line.
  • Example:

``python f = open('data.txt', 'r') line = f.readline() # reads first line print(line) f.close() ``

3. readlines()

  • Reads all lines and returns a list of strings.
  • Example:

``python f = open('data.txt', 'r') lines = f.readlines() for line in lines: print(line.strip()) f.close() ``

Using these methods appropriately helps manage memory and improves program efficiency, especially with large files.

Want to test yourself on File Handling in Python? Try our free quiz →

Writing to Files in Python: Using write() and writelines()

Writing data to files is equally important. Python provides two main methods:

  • write(): Writes a single string to the file.
  • writelines(): Writes a list of strings to the file.

Example using write():

``python f = open('output.txt', 'w') f.write('Hello, Class 12 students!\n') f.write('Welcome to File Handling in Python.') f.close() ``

Example using writelines():

``python lines = ['Line 1\n', 'Line 2\n', 'Line 3\n'] f = open('output.txt', 'w') f.writelines(lines) f.close() ``

Note: writelines() does not add newline characters automatically, so include \n where needed.

MethodWrites Single StringWrites Multiple LinesAdds Newline Automatically
write()YesNoNo
writelines()NoYesNo

Always close the file after writing to ensure data is saved properly.

File Modes in Python: Choosing the Right Mode

Choosing the correct file mode is crucial for your program's success. Here's a quick overview:

ModeDescriptionUse Case
'r'Read onlyReading existing files
'w'Write only (overwrites file)Creating or overwriting files
'a'Append writeAdding data without deleting
'r+'Read and writeModifying files
'w+'Write and read (overwrites file)Creating files with read access
'a+'Append and readReading and appending data

Example:

``python f = open('story.txt', 'a') # Opens file in append mode f.write('Adding new line.\n') f.close() ``

Use raw strings (r'path') for Windows file paths to avoid errors, e.g.,

``python f = open(r'D:\TEMP\story.txt', 'w') ``

This knowledge is essential for Class 12 NCERT exams and practical coding.

Best Practices in File Handling: Closing Files and Error Handling

Proper file handling requires closing files after operations to free system resources and save data. Use close() method:

``python f = open('data.txt', 'r') content = f.read() f.close() ``

Alternatively, use the with statement to handle files automatically:

``python with open('data.txt', 'r') as f: content = f.read() print(content) # No need to call f.close() ``

This ensures files close even if errors occur.

Handling exceptions:

``python try: with open('data.txt', 'r') as f: data = f.read() except FileNotFoundError: print('File not found!') ``

Following these practices prevents data loss and program crashes, important for your Class 12 projects and exams.

Worked Example: Writing and Reading User Input in Python

Let's apply what we've learned with a simple program that writes user input to a file and reads it back line by line.

```python # Writing user input to file with open('user_data.txt', 'w') as f: for i in range(3): data = input(f'Enter line {i+1}: ') f.write(data + '\n')

# Reading and displaying file content with open('user_data.txt', 'r') as f: lines = f.readlines() print('\nContent of file:') for line in lines: print(line.strip()) ```

Explanation:

  • The program writes three lines entered by the user to user_data.txt.
  • It then reads all lines and prints them without newline characters.

This example is typical for Class 12 NCERT practicals and helps understand file handling basics.

Frequently asked questions

What are the common file modes in Python?

Common modes are 'r' for reading, 'w' for writing, 'a' for appending, and 'r+' for reading and writing.

How do you read a file line by line in Python?

Use the readline() method to read one line at a time or iterate over the file object in a loop.

What is the difference between write() and writelines()?

write() writes a single string; writelines() writes a list of strings without adding newlines automatically.

Why should files be closed after operations?

Closing files frees system resources and ensures all data is saved properly to the storage device.

How can I handle errors while opening files?

Use try-except blocks to catch exceptions like FileNotFoundError and handle them gracefully.

Can I read and write to the same file simultaneously?

Yes, by opening the file in 'r+' or 'w+' mode, you can read and write to the same file.

Ready to ace this chapter?

Get the full File Handling in Python chapter — interactive notes, diagrams, worked solutions, polls and a free practice quiz — in the ConceptScroll app.

Open in ConceptScroll →

Study smarter with ConceptScroll

Daily NCERT-aligned reels, AI doubt solving and chapter quizzes — all free.

Start learning free
#class 12#computer science#file handling#file operations#ncert#programming#python#python file modes#read file#write file

Continue reading