FILE HANDLING IN PYTHON-2024
FILE HANDLING IN PYTHON-2024
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
File_object = open(“File_Name","Access_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
file=open("d:\\a.txt")
for l in file:
print(l)
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()
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")
file=open("data.txt", "w")
file=open("data.txt", "w")
name=["Eat healthy\n","Stay
hydrated\n","have adequate sleep\n"]
file.writelines(name)
file.close()
QUICK RECAP
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()
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
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
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
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:
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)