0% found this document useful (0 votes)
48 views49 pages

FILE HANDLING IN PYTHON-2024

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)
48 views49 pages

FILE HANDLING IN PYTHON-2024

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/ 49

FILE HANDLING IN PYTHON

USER INPUT PYTHON PROGRAM OUTPUT ON


KEYBOARD READ DATA WRITE DATA MONITOR
CONSOLE Using input() Using print() CONSOLE
Using file handling your program can read data from a file and write output in
a file as per the requirements

FILE READ DATA PYTHON PROGRAM WRITE DATA FILE

Advantage:
File- storage on hard disk
Input test cases could be in a file, use them multiple times
Output could be stored in a file, read the file to analyse the output
There are two types of files that can be handled in python

Text files: Binary files:


• In this type of file, Each line • It contains information in the same
of text is terminated with a format as in memory. In this type of
special character called EOL file, there is no terminator for a line.
(End of Line), which is the • No translations take place in binary
new line character (‘\n’) in files, hence reading and writing
python by default. binary files through a program is
• Internal translations take faster.
place when text files are • Cannot be read and interpreted by
read or written. us.
• Text files and be read and
interpreted by us.
Opening a File

File_object = open(“File_Name","Access_Mode")

Default is read mode

f=open("d:\\a.txt") No second argument


Default value is
g=open(r"d:\t.txt") “r”…..i.e read mode

h=open("d:\\B.txt“, “w”)
FILE OPENING MODES

Read Only (‘r’) : Open text file for reading. The file pointer is positioned at the beginning of the file. If the file
does not exist, raises the I/O error. This is also the default mode in which a file is opened.
Read and Write (‘r+’): Open the file for reading and writing. The file pointer is positioned at the beginning of
the file. Raises I/O error if the file does not exist.
Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over-written. The
file pointer is positioned at the beginning of the file. Creates the file if the file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-
written. The file pointer is positioned at the beginning of the file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The file pointer is positioned
at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The file
pointer is positioned at the end of the file. The data being written will be inserted at the end, after the existing
data.
Closing a File

f=open("d:\\a.txt")
.
.
f.close()
READING FROM A TEXT FILE
read()
The read() method returns the specified number of bytes from the file. If no
argument given then it returns the entire file’s contents
File: a.txt
This is a text file
File Handling is easy
It is going to be fun

f=open("d:\\a.txt")
s=f.read()
print(s)
f=open("d:\\a.txt")
s=f.read(6)
print(s)

f=open("d:\\a.txt")
s=f.read(19)
print(s)

f=open("d:\\a.txt")
s=f.read(23)
print(s)
readline()
Python file method readline()reads one entire line from the file. A trailing newline character is kept in
the string.

f=open("d:\\a.txt")
s=f.readline()
print(s)
s=f.readline()
print(s)
FOR OUTPUT BASED QUESTIONS

f=open("d:\\a.txt")
s=" "
while s:
s=f.readline()
print(s, end='')

f=open("d:\\a.txt")
s=" "
while s:
s=f.readline()
print(s)
readlines()
The readlines() method returns a list containing each line in the file as a list item.

f=open("d:\\a.txt")
s=f.readlines()
print(s)
WAP Display count of number of lines in a file

f=open("d:\\a.txt")
s=f.readlines()
x=len(s)
print(x)
FOR OUTPUT BASED QUESTIONS

USING A FOR LOOP TO READ A FILE

file=open("d:\\a.txt")
for l in file:
print(l)

You must know this for output based questions


Display lines that start with alphabet “a” or “A”
a.txt EXPLANATION
This is a text file s=[“This is a text file\n”, “Apples are healthy\n”, “File
Apples are healthy handling is easy\n”, “Anger is bad for health\n”]
File Handling is easy
Anger is bad for health FIRST RUN OF THE FOR LOOP
line=“This is a text file\n”
line[0]=‘T’
SOLUTION SECOND RUN OF THE FOR LOOP
file=open("d:\\a.txt") line=“Apples are healthy”
s=file.readlines() Line[0]=‘A’
for line in s: ……….so on
if line[0]=='a' or line[0]=='A':
print(line,end=‘’)
file.close()

For a question in which you have to code, this is the easiest approach
Display lines that start with alphabet “a” or “A”
a.txt EXPLANATION
This is a text file s=“This is a text file\nApples are healthy\nFile
Apples are healthy handling is easy\nAnger is bad for health\n”]
File Handling is easy
Anger is bad for health t=[“This is a text file”, “Apples are healthy”, “File
handling is easy”, “Anger is bad for health”]
SOLUTION-3
file=open("d:\\a.txt") FIRST RUN OF THE FOR LOOP
s=file.read() line=“This is a text file\n”
t=s.split('\n') line[0]=‘T’
SECOND RUN OF THE FOR LOOP
for line in t: line=“Apples are healthy”
if line[0]=='a' or line[0]=='A': Line[0]=‘A’
print(line) ……….so on
file.close()

Alternative approach to the question on the earlier slide, for understanding


Display count of number of digits in the file data.txt
file=open("d:\\a.txt")
count=0
s=file.read()
for ch in s:
if ch.isdigit():
count =count+1
print("Number of digits in the file are: ", count)
file.close()
WRITING INTO A TEXT FILE

write() : writelines() :
File_object.write(str1)
File_object.writelines(L)
Inserts the string str1 in the text file.
Used to insert multiple strings at a single time.
For a list of string elements, each string is inserted in the
text file.
Using write()
file=open("data.txt", "w")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name)
file.close()

write() does not add a


newline character on its
own
Using write()
file=open("data.txt", "w")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name+"\n")
file.close()

file=open("data.txt", "w")

n=int(input("How many names do you want to enter: "))


for i in range(n):
name=input("Enter name: ")
file.write(name)
file.write(“\n”)
file.close()
Using writelines()

file=open("data.txt", "w")

name=["Eat healthy\n","Stay
hydrated\n","have adequate sleep\n"]
file.writelines(name)
file.close()
QUICK RECAP

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split()
print(x)
QUICK RECAP

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split(", ")
print(x)
1. Write a Python program to read and display an entire text file.

f=open("data.txt","r")
s=f.read()
print(s)
f.close()
2. Write a Python program to read first n lines of a file.
f=open("data.txt","r")
n=int(input("How many lines do you want to read: "))
s=f.readlines()
for i in range(n):
print(s[i])
f.close()
3. Write a Python program to display last n lines of a file.

f=open("data.txt","r")
n=int(input("How many lines do you want from end of file: "))
s=f.readlines()
count=len(s)

beg=count-n
s=[line 1, line 2, line 3, line 4, line 5]
last=count
for i in range(beg,last): s[0] s[4]
print(s[i]) Or
s[len(s)-1]
f.close()
Write a Python function countwords() to count number of words in a text file

def countwords():
f=open("content.txt","r")
count=0
s=f.read()
wordlist=s.split()

print("Total number of words in file: ",len(wordlist))

countwords()
5. Write a Python function copy_alternate() to write alternate
lines from a.txt to b.txt
def copy_alternate():
f=open("a.txt","r")
g=open("b.txt","w")

count=0
for line in f:
if count%2==0:
g.write(line)

count=count+1
f.close()
g.close()
File Positions

The tell() method tells you the current position within the file; in
other words, the next read or write will occur at that many
bytes from the beginning of the file.
\n in Windows stored as a pair of
characters CR (Carriage return) and
LF (Line Feed)
File Positions

The seek(offset) method changes the current file position.


The offset argument indicates the number of bytes to be moved from the
beginning of the file.

f.seek(2) ----place the file pointer at 2 bytes from the beginning of the file
f.seek(0) ----place the file pointer at the beginning of the file
fo=open("d:\\info.txt")

s1 = fo.read(9)
print( "First Read : ", s1)

fo.seek(0);
s2= fo.read(9)
print ("First Read : ", s2)

fo.close()
fo=open("d:\\info.txt")

s1 = fo.read(9)
print( "First Read : ", s1)

fo.seek(0);
s2= fo.read(9)
print (“Second Read : ", s2)

fo.close()
File Positions
LEARN (you must
know about reference
position 0,1 and 2)

The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved.

The from argument specifies the reference position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of
the file would be taken as the reference position.

Python 3 does not support movement of file pointer from current or end position.
f.seekg(2) same thing as f.seekg(2,0)
0 as second argument specifies the reference position as beginning of the file
FILE MODES AND OPENING POSITION OF FILE POINTER

POSITION OF FILE POINTER


FILE MODE
Beginning of file
r, r+
Beginning of file, overwrites the file if it
w, w+ exists

At the end of file if it exists, otherwise


a, a+ creates a new file
f=open("d:\\info.txt","r")
print("r mode: ",f.tell())
f.close()

f=open("d:\\info.txt","r+")
print("r+ mode: ",f.tell())
f.close()

f=open("d:\\info.txt","a")
print("a mode: ",f.tell())
f.close()

f=open("d:\\info.txt","a+")
print("a+ mode: ",f.tell())
f.close()

f=open("d:\\info.txt","w")
print("w mode: ",f.tell())
f.close()

f=open("d:\\info.txt","w+")
print("w+ mode: ",f.tell())
f.close()
f=open("d:\\info.txt","r")
print("r mode: ",f.tell()) On executing the Same piece
f.close()
of code again, the output is
f=open("d:\\info.txt","r+")
print("r+ mode: ",f.tell())
f.close()

f=open("d:\\info.txt","a")
print("a mode: ",f.tell())
f.close()

f=open("d:\\info.txt","a+") WHY ??
print("a+ mode: ",f.tell())
f.close()

f=open("d:\\info.txt","w")
print("w mode: ",f.tell())
f.close()

f=open("d:\\info.txt","w+")
print("w+ mode: ",f.tell())
f.close()
Write a Python program to append text to a file and display the text.
f=open("data.txt","a") f=open("data.txt","a+")
n=int(input("How many lines do you want to n=int(input("How many lines do you want to
append: ")) append: "))
for i in range(n):
for i in range(n): s=input("Enter line ")
s=input("Enter line ") f.write(s+"\n")
f.write(s+"\n")
f.flush()
f.close()
f.seek(0)
f=open("data.txt","r") data=f.read()
data=f.read() print("\nFILE CONTENTS\n")
print("\nFILE CONTENTS\n") print(data)
print(data) f.close()
f.close()
What is the output in the file “poem.txt”?
What is the output in the file “poem.txt”?
What is the output?

f=open("d:\\poem.txt","r")
s1=f.readline()
s2=f.read(4)
s3=f.readline()
f.seek(5)
s4=f.readline()

print(s1, end="")
print(s2, end="")
print(s3, end="")
print(s4, end="")

f.close()
flush method and buffering

Buffering is the process of storing data temporarily before it is moved to a


new location.
In the case of files, the data is not immediately written to the disk instead it
is stored in the buffer memory.
This rationale behind doing this is that the writing data to disk takes time as
opposed to writing data to the physical memory. Imagine a program writing
data every time the write() method is called. Such a program would be very
slow.
When we use a buffer, the data is written to the disk only when the buffer
becomes full or when the close() method is called. This process is called
flushing the output. You can also flush the output manually using
the flush() method of the file object. Note that the flush() only saves the buffered
data to the disk. It doesn't close the file.
Usage: f.flush()
ABSOLUTE AND RELATIVE PATHS
An absolute path is a path that describes the location of a file or folder regardless of the
current working directory; in fact, it is from the root directory. It contains the complete
location of a file or directory.

E:\project\a.txt

A relative path is a path that describes the location of a file or folder in relative to the current
working directory.
The symbol . (one dot) can be used for current directory and .. (two dots) denotes the parent
directory.
E:

If the current working directory is Project then


Project Images
..\Images\b.jpg
.\a.txt a.txt b.jpg
STANDARD INPUT OUTPUT AND ERROR STREAMS IN PYTHON

We use file object(s) to work with data files.


Similarly, input/output from devices is also performed using standard I/O stream objects.

stdin , stdout , and stderr are predefined file objects that correspond to Python's standard
input, output, and error streams.

These are file objects which are connected to standard I/O devices.

We use high level functions like input(), print() etc and hence do not use these standard stream objects.
import sys

sys.stdout.write("Hello")
sys.stdout.write("Good Morning")
sys.stdout.write("Hope you are doing fine!!\n")
sys.stdout.write("Using time effectively")
import sys
sys.stdout.write("Enter string: ")
a=sys.stdin.readline()
print("Line read: ",a)

sys.stdout.write("Enter number: ")


number=sys.stdin.readline()
n=int(number)
if n<0:
sys.stderr.write("error")

You might also like