Python File Handling ( UNIT – V )

 

UNIT – v

Python Programming - Python File Handling

1. Introduction

  • File handling in Python allows programs to store data permanently on disk.
  • Files are used to read and write data for future use.
  • Python provides built-in functions such as open(), read(), write(), close() etc., for file operations.

2. Types of Files in Python

Python mainly works with two types of files:

Type

Description

Example

Text Files (.txt)

Store data as readable text (characters). Each line ends with a newline character \n.

student.txt, notes.txt

Binary Files (.bin)

Store data in binary (0s and 1s). Used for images, audio, video, etc.

image.jpg, data.bin


3. Opening a File

Files are opened using the open() function.
Syntax:

file_object = open(filename, mode)

Common File Modes:

Mode

Description

'r'

Read mode (default). File must exist.

'w'

Write mode. Creates new file or overwrites existing one.

'a'

Append mode. Adds data at end of file.

'r+'

Read and write mode.

'w+'

Write and read mode (overwrites file).

'a+'

Append and read mode.

'rb', 'wb', 'ab'

Binary file modes.

Example:

f = open("data.txt", "r")


4. Closing a File

After completing operations, always close the file to free system resources.

Syntax:

f.close()

Example:

f = open("data.txt", "r")

content = f.read()

f.close()

 

Always use close() after file operations or use a with statement (auto-closes the file):

with open("data.txt", "r") as f:

    data = f.read()


5. Reading from a File

Python provides multiple ways to read data:

Method

Description

Example

read()

Reads entire file as a single string

f.read()

read(n)

Reads first n characters

f.read(10)

readline()

Reads one line at a time

f.readline()

readlines()

Reads all lines and returns a list

f.readlines()

Example:

f = open("data.txt", "r")

print(f.read())       # Read entire file

f.close()


6. Writing to a File

(a) write() method

  • Writes a single string to a file.
  • Overwrites existing content if file is opened in 'w' mode.

Example:

f = open("sample.txt", "w")

f.write("Hello Students!\n")

f.write("Welcome to Python File Handling.")

f.close()

Output (in file):

Hello Students!

Welcome to Python File Handling.

 

(b) writelines() method

  • Writes multiple lines at once using a list of strings.
  • Each string must include \n for newlines.

Example:

f = open("student.txt", "w")

lines = ["Arun\n", "Bala\n", "Charan\n"]

f.writelines(lines)

f.close()

Output (in file):

Arun

Bala

Charan


7. Reading and Writing Together

You can open a file in read and write mode using 'r+', 'w+', or 'a+'.

Example:

f = open("demo.txt", "w+")

f.write("Python is fun!")

f.seek(0)        # Move cursor to beginning

print(f.read())  # Read what was written

f.close()


8. File Handling with with Statement

The with keyword automatically closes the file after operations.

Example:

with open("info.txt", "a") as f:

    f.write("New data added!\n")

No need to call f.close() manually.


9. Common File Methods

Method

Description

f.read()

Reads data

f.readline()

Reads one line

f.readlines()

Reads all lines into list

f.write()

Writes a string

f.writelines()

Writes multiple strings

f.tell()

Returns current cursor position

f.seek(pos)

Moves file cursor to position

f.close()

Closes the file


10. Summary (Key Points for Exam)

  • Python uses open() to open a file and close() to close it.
  • File modes: 'r', 'w', 'a', 'r+', 'w+', 'a+'.
  • Text files store readable data; binary files store raw data.
  • write() writes strings; writelines() writes multiple lines.
  • Always use the with statement for automatic file closing.
  • Common operations: reading, writing, appending, and deleting files.

File Handling Methods in Python


1. Introduction

Python provides several built-in file handling methods for creating, reading, writing, appending, and managing files.
The
open() function is used to open files, and file methods are used to perform operations such as reading, writing, and moving within the file.


2. append() Method

  • The append() method is used with file objects opened in 'a' (append) or 'a+' mode.
  • It adds data to the end of an existing file without erasing previous contents.
  • If the file does not exist, Python will create a new file automatically.

Syntax:

file_object = open("filename.txt", "a")

file_object.write("New line added.\n")

file_object.close()

Example:

f = open("notes.txt", "a")

f.write("This line is added later.\n")

f.close()

Appends new data at the end of notes.txt.


3. read() Method

  • The read() method reads the entire content of the file as a single string.
  • You can also specify the number of characters to read.

Syntax:

file_object.read(size)

Example:

f = open("data.txt", "r")

content = f.read()

print(content)

f.close()

Example with Size:

f = open("data.txt", "r")

print(f.read(10))   # Reads first 10 characters

f.close()


4. readlines() Method

  • The readlines() method reads all lines in a file and returns them as a list of strings.
  • Each line in the list ends with a newline character \n.

Example:

f = open("students.txt", "r")

lines = f.readlines()

print(lines)

f.close()

Output:

['Arun\n', 'Bala\n', 'Charan\n']

You can also loop through lines:

for line in lines:

    print(line.strip())  # Removes newline


5. with Keyword

  • The with keyword is used for automatic file handling.
  • It ensures the file is closed automatically after the block of code, even if an error occurs.

Syntax:

with open("file.txt", "r") as f:

    data = f.read()

    print(data)

No need to call f.close().

Advantages:

  • Cleaner code
  • Automatic resource management
  • Prevents file corruption due to unclosed files

6. Splitting Words from a File

To split file content into individual words, use the split() method.

Example:

with open("para.txt", "r") as f:

    data = f.read()

    words = data.split()   # splits by spaces

    print(words)

Output:

['Python', 'is', 'a', 'powerful', 'language']

Note:
split('\n') can be used to split by lines, and split(',') by commas.


7. File Methods

Method

Description

Example

read()

Reads all data

f.read()

readline()

Reads one line

f.readline()

readlines()

Reads all lines into a list

f.readlines()

write()

Writes a single string

f.write("Hello")

writelines()

Writes multiple strings

f.writelines(list)

seek(pos)

Moves cursor to a specific position

f.seek(0)

tell()

Returns current cursor position

f.tell()

close()

Closes the file

f.close()


8. File Positions (seek() and tell())

(a) tell()

  • Returns the current position of the file cursor (in bytes).

Example:

f = open("data.txt", "r")

print(f.tell())  # Output: 0

f.read(5)

print(f.tell())  # Output: 5

f.close()

(b) seek()

  • Used to move the file cursor to a specific position.

Syntax:

f.seek(offset, from_what)

  • offset: Number of bytes to move.
  • from_what: 0 (beginning), 1 (current), 2 (end).

Example:

f = open("data.txt", "r")

f.seek(0)  # Move to beginning

data = f.read(10)

f.close()


9. Renaming and Deleting Files

These operations are performed using the os module.

(a) Renaming a File

import os

os.rename("oldname.txt", "newname.txt")

Changes the file name.

(b) Deleting a File

import os

os.remove("unwanted.txt")

Deletes the specified file.

Note: Before deleting, always check if the file exists using os.path.exists().

Example:

import os

if os.path.exists("sample.txt"):

    os.remove("sample.txt")

else:

    print("File not found!")


10. Summary (Key Points for Exam)

  • append() adds content at the end of the file.
  • read() reads entire file, readlines() reads all lines into a list.
  • with keyword handles automatic closing of files.
  • File positions managed by seek() and tell().
  • Use os.rename() to rename and os.remove() to delete files.
  • Always close files after use (or use with).
  • split() method can be used to separate words from file content.

 

Comments

Popular posts from this blog

PYTHON PROGRAMMING (23UCSCC01) – UNIT - III

Data Structure

PYTHON PROGRAMMING - LAB EXERCISES (23UCSCCP01)