0% found this document useful (0 votes)
4 views81 pages

Text Files

Uploaded by

divyeshragav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views81 pages

Text Files

Uploaded by

divyeshragav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

FILE HANDLING

- TEXT FILES
Reading from File
To read from file,Python provide many functions like :
❑ Filehandle.read([n]) : Reads and return n bytes,
if n is not specified ,it reads entire file.

❑ Filehandle.readline([n]) : Reads a line of input.


If n is specified, reads at most n bytes. Read bytes in
the form of string ending with line character or
blank string if no more bytes are left for reading.

❑ Filehandle.readlines(): Reads all lines and returns


them in a list.
Contents of a.txt
– created by the user
old is gold.
make hay while the sun shines.
Contents of Python program
– Using read( ) without parameter
Code
f1=open("a.txt","r")
s=f1.read() #To read all contents in a file
print(s)
f1.close()
Output
Using read() with parameter

Code
f1=open("a.txt","r")
s=f1.read(5) # To read first 5 characters from the file
print(s)
f1.close()

Output
Using readline( ) –
Without parameter
Code
f1=open("a.txt","r")
s=f1.readline() # To read the first line from the file
print(s)
f1.close()

Output
Using readline( ) – With parameter
Code
f1=open("a.txt","r")
s=f1.readline(10) # To read first 10 characters from the first
line
print(s)
f1.close()

Output
Using multiple readline( )
Code
f1=open("a.txt","r")
s=f1.readline( ) # Reads first line
print(s)
s=f1.readline( ) # Reads second line
print(s)
f1.close( )
Output
Using while loop to read all lines in the file
Code
f1=open("a.txt","r")
s=‘ ‘ # Initially, s contains blank space
while s: # Checks whether s contains content.
# When s is empty, it comes out of the loop
s=f1.readline( ) # s contains first line and goes on
print(s)
f1.close( )
Output
Using for loop to read all lines in the file
Code
f1=open("a.txt","r")
for s in f1: # Every line from file is assigned to s
print(s)
f1.close()

Output
Reading the complete file in a list
- readlines()

Code
f1=open(“a.txt”)
s=f1.readlines( )
print(s)
f1.close()

Output
Program to display the size of a file
in bytes.
Code
f1=open(“a.txt”,’r’)
s=f1.read( )
size=len(s)
print(size)
f1.close()

Output
126
Program to display the number of lines
in the file.

Code
f1=open(“a.txt”,’r’)
s=f1.readlines( )
linecount=len(s)
print(linecount)
f1.close()

Output
2
Program to display the size of a file after
removing EOL characters, leading and
trailing white spaces and blank lines.
Code
f1=open(“a.txt”,’r’)
str=‘ ‘
size=0
while str:
str=f1.readline()
size=size+len(str.strip())
print(“Size of the file after removing spaces & blank lines”,size)
f1.close()
Output
Size of the file after removing spaces & blank lines 124
Write a function stats() that accepts a file name and reports
the file’s longest line.

def stats(filename):
A given text file “para.txt” contains:
f1=open(filename,”r”) His house is in the village
longest=“ “ He will not see me stopping here
To watch his woods fill up
for line in f1:
if len(line)>len(longest):
longest=line
print(“Length of the Longest line=“,len(longest))
print(longest) Output
f1.close() Length of the Longest line= 34
He will not see me stopping here
stats(“para.txt”)
What would be the output of the following code?

fh=open("data1.txt", "r")
lst=fh.readlines()
A given text file “data1.txt” contains:
print(lst) Line 1\n
print(lst[0],end=' ') \n
print(lst[2],end=' ') Line 3
print(lst[5],end=' ') Line 4
\n
print(lst[1],end=' ')
Line 6
print(lst[4],end=' ')
print(lst[3])
Output
Line 1\n
Line 3
Line 6
\n
\n
Line 4
Predict the output of the following code:
fp1=open("p2.txt", "r")
print(fp1.readline(20))
s1=fp1.readline(30)
print(s1)
print(fp1.readline(25))

Contents of p2.txt
A poem by Paramhansa Yogananda
Better than Heaven or Arcadia
I love thee, O my India!
And thy love I shall give
To every brother nation that lives.
Output
A poem by Paramhansa
Yogananda

Better than Heaven or Arc


Functions - Writing onto Files

❖ write() – Writes string to file referenced by


file object.
f1.write(s)

❖ writelines() – Writes all strings in list L


as lines to file referenced by file object.
f1.writelines(L)
Program to write numeric data
to a file
Code
f1=open(“c.txt”,”w”)
x=100
f1.write(“Hello World”)
f1.write(str(x)) write( ) always takes
string as arguments
f1.close()

Output
>>> Blinking cursor indicates the
successful write operation in the file
Contents stored in c.txt

Hello World100
Program to create a file to hold some data.

Code
f1=open(“c1.txt”,’w’)
for i in range(5):
name=input(“enter name of student”)
f1.write(name)
f1.close()

Output
enter name of studentabc
enter name of studentxyz
enter name of studentdef
enter name of studentwxy
enter name of studentmno
Contents stored in c1.txt

abcxyzdefwxymno

Notice that write( ) does not add


a newline character on its own.
Program to create a file to hold some data,
separated as lines.
Code
f1=open(“c1.txt”,’w’)
for i in range(5):
name=input(“enter name of student”)
f1.write(name)
The newline character ‘\n’
f1.write(‘\n’) written after every name
f1.close()
Output
enter name of studentabc
enter name of studentxyz
enter name of studentdef
enter name of studentwxy
enter name of studentmno
Contents stored in c1.txt

abc
xyz Notice that file has newline
def characters at the end of every
name as we added a newline
wxy
after every name.
mno
Program to add list items to a file using
writelines()

Code
f1=open(“c2.txt”,’w’)
list=[“Computer Science\n”,”Maths\n”, “Physics\n”]
f1.writelines(list)
print(“List of lines written successfully”)
f1.close()

Output
List of lines written successfully
Contents stored in c2.txt

Computer Science
Maths
Physics
Appending to file
Code ‘a’ mode allows to add
data to the existing data,
f1=open(“c2.txt”,’a’) instead of overwriting
f1.write(“Chemistry\n”) the data in the file.
f1.write(”English\n”)
print(“More data appended to the file”)
f1.close()

Output
More data appended to the file
Contents stored in c2.txt

Computer Science
Maths
Physics
Chemistry When append mode is
English used, it allows to add
data to the existing data,
instead of overwriting
the data in the file.
Program to get roll numbers, names and marks of
the students of a class and store these details in a
file called “marks.TXT”
Code
count=int(input("How many students are there in the class"))
f1=open("marks.txt",'w')
for i in range(count):
rno=int(input("Enter Roll no"))
name=input("Enter name")
marks=float(input("Enter marks"))
rec=str(rno) + “,"+name+","+str(marks)+'\n'
f1.write(rec)
f1.close()
Output
How many students are there in the class3
Enter Roll no100
Enter nameabc
Enter marks90
Enter Roll no101
Enter namexyz
Enter marks98
Enter Roll no102
Enter namemno
Enter marks99
Contents stored in marks.txt
We have created comma
separated values in one
student record, while
writing in file. So, we can
100,abc,90.0 say that the file created by
program is in CSV(comma
101,xyz,98.0 separated values) format or
102,mno,99.0 it is a delimited file where
comma is the delimiter.
details to the file created
already.
Code
f1=open("marks.txt",‘a')
for i in range(2):
rno=int(input("Enter Roll no"))
name=input("Enter name")
marks=float(input("Enter marks"))
rec=str(rno) + ","+name+","+str(marks)+'\n'
f1.write(rec)
f1.close()
Output
Enter Roll no1
Enter namedef
Enter marks80
Enter Roll no2
Enter namepqr
Enter marks85
Contents stored in marks.txt

100,abc,90.0
101,xyz,98.0
102,mno,99.0
1,def,80.0
2,pqr,85.0
Program to display the
contents of file “marks.TXt”
created.
Code
f1=open("marks.txt",‘r')
for s in f1: or s=‘ ‘ or s=f1.read()
print(s) while s: print(s)
f1.close() s=f1.readline()
print(s)
Output
100,abc,90.0
101,xyz,98.0
102,mno,99.0
1,def,80.0
2,pqr,85.0
Output - for loop & readline( )

100,abc,90.0

101,xyz,98.0

102,mno,99.0

1,def,80.0

2,pqr,85.0
Using writelines()
f1=open("emp.txt","w")
l=[ ]
for i in range(3):
name=input("enter employee name")
l.append(name+'\n')
f1.writelines(l)
f1.close()
print("Data saved")

Output
enter employee nameabc
enter employee namedef
enter employee namexyz
Data saved
Contents stored in emp.txt

abc
def
xyz
program to display the contents of file
“emp.txt” created.
Code
f1=open(“emp.txt",‘r')
for l in f1: or s=‘ ‘ or s=f1.read()
print(l) while s: print(s)
f1.close() s=f1.readline()
print(s)

Output
abc Output Output
abc abc
def def
def
xyz
xyz xyz
Using readlines()

Code
f1=open(“emp.txt",‘r')
s=f1.readlines()
print(s)
f1.close()

Output
['abc\n', 'def\n', 'xyz\n']
Write a program that copies a text file “source.txt” onto
“target.txt” barring the lines starting with ‘@’ sign.

def filter(oldfile,newfile):
f1=open(oldfile,'r')
f2=open(newfile,'w')
while True:
Contents of “source.txt”
text=f1.readline()
@India is my@ countr@y
if len(text)==0: All Ind@ians are my bro@thers and si@sters
break @I love my country
if text[0]=='@':
continue
f2.write(text) Contents of “target.txt”
f1.close() All Ind@ians are my bro@thers and si@sters
f2.close()
filter(“source.txt",“target.txt")
Write a program remove_lowercase() that accepts two file names,
and copies all lines that do not start with a lowercase letter from the
first file into the second.

def remove_lowercase(infile,outfile):
f1=open(infile,‘r') A given text file “para.txt” contains:
f2=open(outfile,‘w') His house is in the village
he will not see me stopping here
for line in f1: To watch his woods fill up
if not line[0].islower():
f2.write(line) Contents of para1.txt
His house is in the village
f1.close() To watch his woods fill up
f2.close()
remove_lowercase("para.txt","para1.txt")
1. A file sports.dat contains information in following
format: Event – Participant
Write a function that would read contents from file
sports.txt and creates a file named Athletic.txt,
copying only those records from sports.txt where
the event name is “Athletics”.

2. Write a function that accepts two file names, and


copies all those words that do not start with an
uppercase vowel from the first file into the second.
1.TO COPY FROM ONE FILE TO
ANOTHER FILE

def copy(file1,file2):
Contents of sports.txt
f1=open(file1,"r")
Football-abc
f2=open(file2,"w") Athletics-xyz
for i in f1:#readline()
x=i.split('-')#x=[“Athletics”,”xyz”]
if x[0]=='Athletics':
Contents of
f2.write(i) Athletic.txt
f1.close() Athletics-xyz
f2.close()
copy("sports.txt","Athletic.txt")
2.TO COPY words that do not start with uppercase
vowel from first FILE to second file
def copy(file1,file2): Contents of a2.txt
f1=open(file1,"r") All that glitters Is not gold
f2=open(file2,"w") Make hay while the sun shines
s=f1.read()
word=s.split() #word=[“All”,”that”,”glitters”,…….”shines”]
for x in word:
if x[0] not in "AEIOU":
f2.write(x+' ')
f1.close() Contents of a3.txt
f2.close() that glitters not gold Make hay while the sun shines
copy("a2.txt","a3.txt")
To copy the content of one file
to anotherfile
flush() function
▪ When we write any data to file, python hold
everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to
force Python to write the content of buffer
onto storage, you can use flush() function.

▪ Python automatically flushes the files when


closing them i.e. it will be implicitly called by
the close(), BUT if you want to flush before
closing any file you can use flush().
working of flush( )
Nothing is in
the file
temp.txt
Without flush()

When you run the above code, program will


be stopped at “Press any key”, for time
being don’t press any key and go to folder
where file “temp.txt” is created and open it
to see what is in the file till now
NOW PRESS ANY KEY….

Now content is stored,


because of close() function
contents are flushed and
pushed in file
of flush() All contents
before flush()
With flush() are present
in file

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where
file “temp.txt” is created an open it to see
what is in the file till now
PRESS ANY KEY….

Rest of the content is


written because of close(),
contents are flushed and
pushed in file.
Write a user defined function in Python that displays the

number of lines starting with ‘H’ in the file ‘Para.txt’.

def countH():
f1=open(“Para.txt”,”r”)
c=0 Contents of Para.txt
for i in f1: His house is in the village
He will not see me stopping here
if i[0]==‘H’: To watch his woods fill up

c+=1
print(“No. of lines starting with H”,c)
f1.close() Output
No. of lines starting with H 2
Write a user defined function countmy() in
Python that counts the number of times “my”
occurs in the file ‘Data.txt’.

Contents of Data.txt
def COUNTMY(): My house is in the village
f1=open(“Data.txt","r") I live with my parents
To watch his woods fill up
c=0
x= f1.read()
Output
word=x.split() [“My”, “house”, ”is”, “in”
print(word) “the”, ”village” , ”I”, ”live”
for i in word: “with”, “my”, “parents”,
if i=='my‘: “To”, “watch”, “his”,
”woods”, “fill”, “up”]
c+=1
print("my occurs",c,"times") my occurs 1 time
f1.close()
Write a user defined function Displaywords() in Python to
read lines from a text file “POEM.txt” and display those
words which are less than 4 characters.

def Displaywords(): Contents of POEM.txt


My house is in the village
f1=open(“POEM.txt","r") I live with my parents
x= f1.read() To watch his woods fill up

word=x.split() Output
My
for i in word: is
in
if len(i)<4: the
I
print(i) my
f1.close() To
his
up
Write a user defined function in Python to count the
number of uppercase alphabets present in a text file
“Poem.txt”.
def uppercase():
f1=open("Poem.txt","r")
x= f1.read() Contents of “Poem.txt”
c=0 India is my Country.
All Indians are my Brothers and Sisters.
for i in x:
if (i.isupper()): Output
Number of uppercase characters 6
c+=1
print("Number of uppercase characters",c)
f1.close()
Write a program to display all the records in a file
along with line/record number.
f1=open("result1.txt",'r')
count=0 # For writing contents in
for rec in f1: #readline() result1.txt
f1=open(“result1.txt”,”w”)
count=count+1 for i in range(2):
print(count,rec,end=‘’) eno=int(input(“enter no”))
name=input(“enter name”)
f1.close()
sal=float(input(“enter sal”))
rec=str(eno)+’,’ +name+’,’+str(sal)
f1.write(rec)
f1.close()
Contents of “result1.txt” Outputtput
100,abc,20000.0 1 100,abc,20000.0
101,xyz,30000.0 2 101,xyz,30000.0
Write a user defined function in Python to print the last

line of a text file ‘data.txt’.

def lastline():
f1=open(“data.txt","r")
x= f1.readlines()
print(“Last Line=“,x[-1])
f1.close()
Contents of data.txt Output
My house is in the village
Last Line= To watch his woods fill up
I live with my parents
To watch his woods fill up
Removing whitespaces
after reading from file
❖ read() and readline() reads data from file and
return it in the form of string and readlines()
returns data in the form of list.
❖ All these read function also read leading and
trailing whitespaces, new line characters. If you
want to remove these characters, you can use
functions:
✓ strip() : removes the given character from both
ends.
✓ lstrip(): removes given character from left end.
✓ rstrip(): removes given character from right end.
strip(),lstrip(),rstrip()
CODE

OUTPUT CONTENTS OF IPL.TXT


File Pointer
❖ Every file maintains a file pointer which tells the
current position in the file where reading and
writing operation will take.

❖ When we perform any read/write operation,


two things happen:
✓ The operation at the current position of file pointer.
✓ File pointer advances by the specified number of
bytes.
Example
myfile = open(“ipl.txt”,”r”)

File pointer will be by default at first position i.e. first character

ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
File Modes and Openingposition of file pointer

FILE MODE OPENING POSITION


r, r+, rb, rb+ or r+b Beginning of file.

w, w+, wb, wb+ or w+b Beginning of file (overwrites


the file, if file already exists).

a, ab, a+, ab+ or a+b At the end of file, if file


exists. Otherwise creates a
new file.
Random Access Methods – seek() & tell()
Files in Python allow random access of the data
as well using built-in methods - seek() and tell().

➢ seek() - used to change the position of the


file handle (file pointer) to a given specific
position. File pointer is like a cursor, which
defines from where the data has to be read or
written in the file.
Fileobject.seek(offset,[reference point])

➢ tell() – gives the current position of the file


pointer.
Fileobject.tell()
seek()
❖Python file method seek() sets the file’s current
position. First argument is offset which moves the
number of bytes to the required position.

❖The second argument(reference point) is optional and


defaults to 0, which means absolute file positioning.
✓ 0: sets the reference point at the beginning of
the file, which is by default.
✓ 1: sets the reference point at the current file
position. Works only with binary files.
✓ 2: sets the reference point at the end of the file.
Works only with binary files.
tell() and seek() - text files
f=open("a2.txt")
print(f.tell()) # 0 Contents of a2.txt
s=f.read()
All that glitters Is not gold
print(f.tell()) # 70
Make hay while the sun
f.seek(0)
shines
print(f.tell()) # 0
f.seek(10) NEGATIVE INDEXING
print(f.tell()) #10
f.read(3)
WILL NOT WORK
print(f.tell()) #13 IN TEXT FILES.
f.seek(3)
print(f.tell()) #3 ONLY REFERENCE POINT 0
f.read(3)
WILL WORK IN TEXT FILES.
print(f.tell()) #6
f.close()
Output
0
70
0
10
13
3
6
tell() and seek() in binary files
f=open("proj1.dat",'rb')
print(f.tell()) #0
s=f.read() Second Parameter in seek()
print(f.tell()) #57
0 – From Beginning of file– Default
f.seek(0)
1 – From Current position of file
print(f.tell()) #0
2 - From the end of file
f.seek(10)
print(f.tell()) #10
f.read(3) NEGATIVE
print(f.tell()) #13
INDEXING
f.seek(-3,2)
print(f.tell()) #54 WILL WORK ONLY
f.read(3) IN BINARY FILES
print(f.tell()) #57
f.close()
Output
0
57
0
10
13
54
57
Standard INPUT, OUTPUT and ERROR
STREAM
▪ Standard Input : Keyboard
▪ Standard Output : Monitor
▪ Standard error : Monitor
▪ Standard Input devices(stdin) read from
keyboard.

▪ Standard output devices(stdout) display output


on monitor.

▪ Standard error devices(stderr) same as stdout


but normally for errors only.
STANDARD INPUT, OUTPUT AND ERROR STREAM
✓ The standard devices are implemented as files called
standard streams in Python and we can use them by
using sys module.
✓ After importing sys module, we can use standard
streams stdin, stdout, stderr.
CODE(Y13.PY)

OUTPUT
“with” statement
▪ Python’s “with” statement for file handling is
very handy when you have two related
operations which you would like to execute as a
pair, with a block of code in between:
with open(filename[, mode]) as filehandle:
file_manipulation_statement

▪ The advantage of “with” is, it will automatically


close the file after nested block of code. It
guarantees to close the file how nested block
exits even if any run time error occurs.
Example
Absolute Vs Relative PATH
▪ To understand PATH ,we must be familiar with the
terms: DRIVE, FOLDER/DIRECTORY, FILES.
▪ Our hard disk is logically divided into many
parts called DRIVES like C DRIVE, D DRIVE etc.
▪ D:\XII\XII A\a.txt – Absolute Path
Absolute Vs Relative PATH

▪ The drive is the main container in which we


put everything to store.
▪ The naming format is : DRIVE_LETTER:
▪ For e.g. C: , D:
▪ Drive is also known as ROOT DIRECTORY.
▪ Drive contains Folder and Files.
▪ Folder contains sub-folders or files
▪ Files are the actual data container.
Absolute Vs Relative PATH
DRIVE
FOLDER
DRIVE/FOLDER/FILE HIERARCHY

C:\

DRIVE

SALES IT HR PROD
FOLDE R FOLDE R
E FOLDE R FOLDE R

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDE R FOLDE R FILE FOLDE R FOLDE R

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE
Absolute Path
Absolute path is the full address of any file or
folder from the Drive i.e. from ROOT FOLDER. It
is like:
✓ Drive_Name:\Folder\Folder…\filename

▪ For e.g. the Absolute path of file


REVENUE.TXT will be
 C:\SALES\2018\REVENUE.TXT
▪ Absolute path of SEC_12.PPT is
 C:\PROD\NOIDA\Sec_12.ppt
Relative Path
▪ Relative Path is the location of file/folder from the
current folder. To use Relative path,
special symbols are:

 Single Dot ( . ) : single dot ( . ) refers to current


folder.

 Double Dot ( .. ) : double dot ( .. ) refers to


parent folder.

 Backslash ( \ ) : first backslash before(.)


refers to current folder and double dot( .. ) refers
to ROOT folder.
Relative addressing
Current working directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : SALES


WE WANT TO ACCESS SHEET.XLS FILE,THEN RELATIVE ADDRESSWILL BE

.\2019\SHEET.XLS
Relative addressing
Current working
directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : DELHI


WE WANT TO ACCESS SEC_8.XLS FILE,THEN RELATIVE ADDRESS WILL BE
..\NOIDA\SEC_8.XLS
Getting name of current
working directory
import os
pwd = os.getcwd()
print("Current Directory :",pwd)

OUTPUT
Current Directory
C:\Users\AppData\Local\Programs\Python\Python37-32

You might also like