0% found this document useful (0 votes)
82 views10 pages

Class XII - File Handling Text Files

The document discusses working with text files in Python. It covers opening and closing files, reading from files using functions like read(), readline(), and readlines(), and writing to files using write() and writelines(). It also discusses different file modes for opening files, performing read and write operations, and some common file problems and solutions in Python like reading a file line by line or character by character. Sample programs are provided for reading a file and copying it to a new file.

Uploaded by

Nishan Sidhu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
82 views10 pages

Class XII - File Handling Text Files

The document discusses working with text files in Python. It covers opening and closing files, reading from files using functions like read(), readline(), and readlines(), and writing to files using write() and writelines(). It also discusses different file modes for opening files, performing read and write operations, and some common file problems and solutions in Python like reading a file line by line or character by character. Sample programs are provided for reading a file and copying it to a new file.

Uploaded by

Nishan Sidhu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Chapter 5 – Part 1

File handling – Text Files


Class – XII
Subject: Computer Science

Data File Handling

Class XII

What is a data file and why we need to work with files in Python—

Data File - Data stored on permanent storage in computer is called data file. Each data file has a specific name.

Why we need data files in programming-

When a program runs, it generally stores its data in RAM, which is volatile memory. Means data is not
permanently stored. In such programs, data related to program gets washed away as soon as the program ends.

But what if you want to permanently store data of a program? To be able to do so, we need to store it on
permanent storage. There are generally two options to permanently store your data-

1. Using Database- we studied what is database and how to insert/modify data into database using SQL in
previous class. We can connect python program to database and store program data into database. We
will study this later.
2. Using data files - We can store program data into permanent storage using data files.

File Operations –

1. Opening a File – To open a new or existing file.


2. Closing a File – To close a file.
3. Reading File – Reading data from file.
4. Writing File – Writing data into an empty file.
5. Appending File – Adding data at the end of existing file

Types of data files –

1. Text File – Data is stored in the form of human readable text (either ASCII or UNICODE)
2. Binary File - Data is stored in binary form which is not human readable.
3. CSV(Comma Separated Values File) : Data values are separated by commas. It can be viewed in tabular
form.

Working With Text Files

Opening and Closing Files – Before doing any other operation on file, we need to open it in our program.

Syntax to open a file-

<File_handle> = open(“<File Name with Path>”,”<File Mode>”)

File Handle – It is an identifier that is linked to file after opening it. File handle is used for further working with
the file.

File Mode –It is the mode in which you want to open a file. There are 3 basic file modes – r (read only), w (write
only) and a (append)

Example—

Let’s say we want to open Employees.txt in read mode. Following statement will do the work –

MyFile = open(“Employee.txt”,”r”)

Syntax to close a file-

<File_object>.close()

Example –
MyFile.close()

File Modes in detail–

1. r – (read mode)
 To open a file in read only mode.
 Writing is not allowed
 If file does not exist, It gives error
2. w—(Write Mode)
 To open a file in write only mode
 reading is not allowed
 If file does not exist, new blank file is created.
 If file exist already, existing data is truncated/deleted.
3. a – (Append Mode)
 To open a file in append mode
 Reading is not allowed
 If file not exist, new blank file is created.
 If file exist already, existing data is NOT truncated/deleted.
4. r+ – (Read and Write mode)
 Both reading and writing is allowed
 If file does not exist, It gives error
5. w+ – (Write and Read mode)
 Both reading and writing is allowed
 If file does not exist, new blank file is created.
 If file exist already, existing data is truncated/deleted.
6. a+ – (Append and Read mode
 Both reading and writing is allowed
 If file not exist, new blank file is created.
 If file exist already, existing data is NOT truncated/deleted.

PERFORMING READ OPERATION ON TEXT FILES

STEPS—

(I) Open the file in any read mode (i.e. r,r+)


(II) Use below mentioned functions to read data from opened file.
Functions for Read Operation—

1. read(n) - read n number of characters from file. But if n is not given, it will read entire file. It returns
data in the form of string.
2. readline(n) – It will read one line at a time, if n is specified, it will read first n characters of each line.
It returns data in the form of string.
3. readlines() – to read all lines of a file in a LIST. It returns a List.
Exxamples—

1. Write a program to read a file Student.txt and print its contents.


Suppose File content is as below–

Answer -

MYFILE = open("Student.txt","r")
A = MYFILE.read() I am a dummy file
print(A) >>>
MYFILE.close() Output

2. Write a program to read first 5 characters from a file and print it.
Suppose File content is as below–

ANSWER -

MYFILE = open("Student.txt","r")
A = MYFILE.read(5) I am
print(A) >>>>>>
MYFILE.close() Output

3. Write a program to read a file Student.txt character wise, means reading should be done one
character at a time and print its each character in new line.
Suppose File content is as below–
ANSWER—

MYFILE = open("Student.txt","r")
A = MYFILE.read(1) d
while A: u
print(A) m
A = MYFILE.read(1)
m
MYFILE.close()
y
Output
>>>

PERFORMING WRITE OPERATION ON TEXT FILES

STEPS—

(I) Open the file in any write mode (i.e. w,w+,a,a+)


(II) Use below mentioned functions to write data into opened file.

Functions for Write Operation—

1. write(<str>) - write string <str> into file. It does not insert newline(‘\n’) so newline has to be
inserted manually..
2. writelines(<list>) – to write all lines of a List <list> into file.

Example—

1. A simple program to create a text file--


F=open("output.txt", “w”) >>>>>>
Data = “My First Text File”
F.write(Data) Output
F.close()

Above program will create a file “output.txt” and write the contents into it.

2. Write a program in python to create a text file using writelines() function.

F=open("input.txt", “w”) >>>>>>


Data = [“My First Text File\n”,
“This is my first text file\n”, Output
“Created through Python\n”]
F.writelines(Data)
F.close()

Here we have manually inserted newline (“\n”) at the end of each line because write() or writelines()
functions do not automatically insert newline.

Absolute and Relative Paths

Pathname: full name of a file along with directory structure is called its path or pathname.
Absolute Path: Path of a file from top level directory(root) is called Absolute path.
For example—
E:\MyData\Python\Files\Student.txt

Relative Path: Path of a file with respect to current working directory (CWD) is called relative path.
For Example—
.\Files\Student.txt

Current Working Directory is denoted by dot(.)


Parent directory of CWD is denoted by two dots (..)

1. Write a program to read data from a file using absolute path of file.

F=open(r"D:\Data\input.txt") Contents of File


S = F.read() >>>>>>
print(S) Output
2. Write a program to read data from a file using relative path of file.

F=open(r".\input.txt") Contents of File


S = F.read() >>>>>>

print(S) Output

File.seek( n,m)

N - number of positions to move

M – from where to count the number of position

0 – Beginning of the file

1 – Current position

2 – from end of the file

Methods for Solving Common File Problems


1. Whether you want to read file in a one go
Data = FileHandle.read()
2. Or You need to read the file line by line
for L in FileHandle:
<Process line L>
3. Or You need to read a file word by word:
Data = FileHandle.read()
Word = Data.split()
For w in Words :
<process w>

4. Or you need to read the file character by character.


Data = FileHandle.read()
for C in Data:
<process character C>

SOME IMPORTANT TEXT FILE PROGRAMS


1. Write a program in Python to read a text file INPUT.txt and Copy it in INPUT_COPY.txt

#Program to read a file One.txt and


>>>>>>
#create its copy Two.txt
File1 = open("One.txt","r")
File2 = open("Two.txt","w")
STR = File1.read() Output
File2.write(STR)
File1.close()
File2.close()

2. Write a program to read a file INPUT.txt and copy lines starting with letter ‘D’ to another file
OUTPUT.txt.

#Program to read a file One.txt and create its copy


Two.txt >>>>>>

File1 = open("Input.txt","r")
File2 = open("Output.txt","w")
for LINE in File1: Output
if LINE[0] == 'D':
File2.write(LINE)
File2.write('\n')
File1.close()
File2.close()

3. Write a program in python to replace a word ‘Dhenkanaal’ by ‘Dhenkanal’ in a file CITY.txt

import os
FH_I = open("INPUT.txt","r") >>>>>>
FH_O = open("OUTPUT.txt","w")
for LINE in FH_I:
WORDS = LINE.split() Output
L = len(WORDS)
4. Write a program to delete a line containing word ‘Password’ from a file input.txt

#A program to delete lines cotaining word "Password" from a


file. >>>>>>
import os
FILE = open("INPUT.txt","r")
Output
TEMP = open("Temp.txt","w")
for L in FILE:
if "PASSWORD" not in L.upper():
TEMP.write(L)

FILE.close()
TEMP.close()

os.remove("INPUT.txt")
os.rename("Temp.txt","INPUT.txt")
STANDARD INPUT/OUTPUT and ERROR STREAMS

Standard Output Device : Monitor


Standard Input Device: Keyboard
Standard Error : Monitor

Standard Output Stream : It is a file attached to Standard Output device. Whatever is written into this
file is displayed on monitor.
To use these files, we have to import sys module.
File Name is sys.stdout

Standard Input Stream : It is a file attached to Standard Input device (Keyboard). Whatever is written
into this file will be taken as input.

File Name = sys.stdin

Standard Error Stream : It is a file attached to standard error device.

File Name = sys.stderr

You might also like