DATA FILE HANDLING PART-1
TOPICS- INTRODUCTION TO FILES
❖ What is a file?
❖ Purpose of files in Python
❖ Basic operations in files
❖ Types of Files
❖ Path
❖ Steps in File handling
File
A file is a named location on a secondary media where data are permanently stored for later access.
A file contains data as bunch of bytes.
Purpose of Files
Basic Operations in Files
❖ Reading from files
❖ Writing into files
❖ Appending data to files
Reading data from Files
➢ You may or may not specify the ‘r’ mode as the file is by default opened in read mode.
➢ If the file doesn’t exist, then the file not found error occurs.
➢ When the file is opened in ‘r’ mode, then the File Pointer moves to the beginning of the file.
Writing into the file
❑ If the file already exists, all the contents will be overwritten in ‘w’ mode.
❑ If the file doesn’t exist, then a new file will be created.
❑ File pointer placed in the beginning of file
Appending data to a file
❖ Appending means to add the data at the end of file using ‘a’ mode.
❖ If file doesn’t exist, it will create the new file.
❖ If file exists, it will append the data at the end of a file.
❖ File pointer will be placed at the end of the file.
Types of Files
➢ Text File
➢ Binary File
➢ CSV File
TEXT FILE
➢ Text file stores information in the form of ASCII or Unicode characters (letters, numbers, symbols etc.), which
means in a human readable format.
➢ Each line is terminated by a special character, known as End of line(EOL).By default, this EOL character is the
newline character(\n).
➢ It is the default mode of file.
➢ Text files are having the extension .txt.
BINARY FILES
➢ Binary files are stored data in the form of bytes( 0s and 1s) and they do not represent ASCII characters.
➢ They represent the actual contents such as image, audio, video, compressed versions of other files, executable
files, etc.
➢ These files are not human readable, thus trying to open a binary file using text editor shows some garbage
values.
➢ We need specific software to read or write the contents of a binary file.
➢ Binary files are having the extension .dat.
CSV FILES
✓ CSV stands for Comma Separated Values.
✓ CSV just like a text file, it is human readable format, used to store data in tabular form(in the form of rows and
columns)like a spreadsheet or database.
✓ The separator character of CSV file is called a delimiter. Default delimiter is comma(,). Other than comma,
tab(\t),colon(:),pipe(|) and semicolon(;) also used.
✓ So, CSV is a delimited text file, that uses a comma to separate values from one another.
✓ Extension is .csv
PATH
➢ A path is a string that specifies the location of a file or directory on the file system i.e., complete name of a
file/directory is called pathname.
➢ Path can be either absolute or relative.
ABSOLUTE PATH
❖ It specifies the complete location of a file/directory on the file system, starting from root directory.
Eg. D:\Path\dd.txt or D:\Path\xyz.txt
D is the root directory
RELATIVE PATH
❖ It specifies the location of a file or directory relative to the current working directory. The symbol . used in
place of current directory and .. denotes the parent directory.
Eg. Current working directory is Path and the relative pathname is
.\xyz.txt or .\dd.txt
To access from root directory
..\Path\xyz.txt
Steps in file handling
❖ Open a file
❖ Process the file
❖ Close a file
Opening a file
❖ It establishes the link between file object and external file.
Syntax:
<file object>=open(<file_name>, <file mode>)
Eg. x=open(“xyz.txt”)
y=open(“dd.txt”,”w”)
b=open(“xyz.txt”,a)
If the file is in different location other than Python,
x=open(“D:\\Path\\xyz.txt”,a)
X=open(r”D:\Path\xyz.txt”w)-raw string
Open a file using with statement- Resources are automatically released after the usage.
Syntax:
with open(<file_name>,<file mode>)as <file object>:
<file manipulation statements>
Eg:
With open(“xyz.txt”,”r”)as x:
y=x.read()
print(y)
File Open Modes
Closing a file
• Breaks the link of file object and external file on the disk.
• Once we done with the read/write operations on a file, it is a good practice to close the file.
• While closing a file, system frees the memory allocated to it.
Syntax:
<file_object>.close()
Eg: x.close()
TEXT FILES
Topics-
❖ Writing to a Text file
❖ Reading from a Text file
❖ Random Access of data
❖ Data manipulation of files
Writing to a Text file
For writing to a file, we first need to open it in write mode or append mode.After opening , we can use the
following methods to write data in the file.
➢ write()
➢ writelines()
1. write() method
write() method takes a single string as an argument and write it into the text file. It returns the no. of
characters being written on single execution.also, we need to write a newline character(\n) at the end of
every sequence to mark the end of line.
Syntax:
<file_object>.write(string)
Eg. >>>F=open(“myfile.txt”,”w”)
>>>F.write(“Welcome to Python files\n”)
41 # no. of characters
>>>F.close()
For storing numeric values, we have to either convert it into string using str() or write it in quotes.
Eg. >>>F=open(“myfile.txt”,”w”)
>>>marks=58
>>> F.write(str(marks))
2 # no. of characters
>>>F.close()
Examples
Writing a single line string in a text file
def WRITE():
F=open(“myfile.txt”,”w”)
F.write(“This is my first program”)
F.close()
WRITE()
OR
def WRITE():
F=open(“myfile.txt”,”w”)
Str=input(“Enter the line:”)
F.write(Str)
F.close()
WRITE()
Writing multiple lines of string in a text file
def WRITE():
F=open(“myfile.txt”,”w”)
F.write(“This is my first program”)
F.write(“Python Programming is fun”)
F.write(“It is case sensitive”)
F.close()
WRITE()
OR
def WRITE():
F=open(“myfile.txt”,”w”)
While True:
Str=input(“Enter the line:”)
F.write(Str+’\n’)
Ch=input(“More lines to enter(Y/N)
If Ch==’N’ or Ch==’n’
break
F.close()
WRITE()
2. writelines() method
➢ It is used to write multiple strings in a file( string, list, tuple etc.)
➢ ‘\n’ required for line break
➢ It does not return the no. of characters in single execution.So it is a void function.
Syntax:
<file_object>.writelines(List/string/Tuple)
Eg. def WRITE():
F=open(“myfile.txt”,”w”)
L=[“Python Programming\n”,”File Handling\n”,”Text Files”]
F.writelines(L)
F.close()
WRITE()
Reading data from files( r,r+,w+,a+)
Python provides mainly 3 types of read functions to read from a data file.
Syntax:
<file_obj>.read() - return a single string
<file_obj>.readline() – read single line as a string
<file_obj>.readlines()- read entire content as a list
Examples:
1. read() method
Reading 10 bytes from the text file myfile.txt OUTPUT:
def READ(): PYTHON PRO
F=open(“myfile.txt”)
Str1=F.read(10)
print(Str1)
F.close()
READ()
Reading 10 bytes from the text file myfile.txt and then read 20 bytes from the file.
def READ(): OUTPUT:
F=open(“myfile.txt”) PYTHON PRO
Str1=F.read(10) GRAMMING
print(Str1) FILE HANDLI
Str2=F.read(20)
print(Str2)
F.close()
READ()
Reading the entire content of file myfile.txt
def READ(): PYTHON PROGRAMMING
F=open(“myfile.txt”) FILE HANDLING
Str1=F.read() TEXT FILES
print(Str1)
F.close()
READ()
2. readline()
eg. Reading the first 3 lines of file myfile.txt
def READ(): OUTPUT:
F=open(“myfile.txt”) PYTHON PROGRAMMING
Str1=F.readline() FILE HANDLING
print(Str1) TEXT FILES
Str2=F.readline()
print(Str2)
Str3=F.readline()
print(Str3)
F.close()
READ()
Reading myfile.txt line by line
def READ():
F=open(“myfile.txt”)
Str1=” “
while Str1:
Str1=F.readline()
Print(Str1,end=” “)
F.close()
READ()
Reading myfile.txt line by line without leading and trailing spaces.
def READ():
F=open(“myfile.txt”)
Str1=” “
while Str1:
Str1=F.readline()
print(Str1.strip())
F.close()
READ()
Reading the first 3 characters of each line of file.
def READ()
F=open(“myfile.txt”)
Str1=” “
while Str1:
Str1=F.readline(3)
print(Str1)
F.close()
READ()
3. readlines()
Eg. Reading the complete file in a list
def READ(): OUTPUT:
F=open(“myfile.txt”) [“PYTHON PROGRAMMING\n”,FILE HANDLING\n”,TEXT FILES”]
Str1=F.readlines()
print(Str1)
F.close()
READ()
Random access of data in files
seek()
This method is used to position the file object at a particular position in a file.
Syntax:
<file_obj>.seek(offset,[reference point])
Offset- No. of bytes by which the file object is to be moved.
Reference point- It indicates the starting position. It takes 3 values.
0 – sets reference point at the beginning of the file
1 - sets reference point at the current position of the file
2 - sets reference point at the end of the file
tell() method – This methos returns an integer that specifies the current position of the file object in the file.
Syntax:
<file_obj>.tell()
Eg.
def READ():
F=open(“myfile.txt”) OUTPUT:
print(F.tell()
print(F.read()
F.seek(6)
print(F.read()
F.seek(4)
print(F.read(5)
print(“Current position of FP”,F.tell())
F.close()
READ()
DATA MANIPULATION OF TEXT FILES
Data manipulation refers to replacing certain specific parts from data with new data.
replace()- this function is used to replace specified phrase of data with another specified phrase of data
Syntax:
string.replace(old_phrase,new_phrase,count)
Program
i=open(“abc.txt”)
x=i.read()
print(“Original data is :\n”,x)
y=input(“Enter the string to be replaced:\n”)
z=input(“Enter the new string:\n”)
out=open(“abc.txt”,”w+”)
out.seek(0)
f=out.read()
print(“Updated data is:\n”,f)
i.close()
out.close()
Example Programs
Write a program to display the size of the file.
X=open(“myfile.txt”)
Str1=X.read()
print(“Size of the file is:”,len(Str1))
X.close()
Write a program to read the last line of the file
X=open(“myfile.txt”)
Str1=X.readlines()
print(Str1[-1])
X.close()
Write a program to count the no. of lines from the file.
X=open(“myfile.txt”)
Str1=X.readlines()
print(“No. of lines is:”,len(Str1))
X.close()
Write a program to add names of 2 students and then read it.
X=open(“myfile.txt”)
for i in range(0,2):
name=input(“Enter the name of the student”)
X.write(name+’\n’)
X.seek(0)
Z=X.read()
Print(“Data in disk:\n”,Z)
X.close()
Program to receive Roll no and Name of n students of a class in a text file a_data.txt and display the same.
n=int(input(“Enter the no. of students in the class\n:”))
X=open(“a_data.txt”,”w+”)
X.write(“Roll\tName\n”)
for i in range(0,n):
roll=int(input(“Enter the roll no:”))
X.write(str(roll)+’\t’)
name=input(“Enter the name:”)
X.write(name+’\n’)
X.seek(0)
Y=X.read()
print(y)
X.close()
************************