File Handling Text+Binary+CSV
File Handling Text+Binary+CSV
f=open(“Myfile.txt”)
f is known as file
or
object, file handle
f=open(“Myfile.txt”,“r”) or file variable
f is known as file
object, file handle
or file variable
f.close()
>>>f=open(r"C:\Users\Saurabh\Desktop\Homework.txt", "r")
>>> f.close()
>>> f=open(r"D:\India.txt", "w")
>>> f.write("Hello")
5
>>> f.close()
1. read function -
The read() method reads the entire file and returns its
contents in the form of a string.
>>> f=open("abc.txt","r")
>>> s=f.read()
>>> print(s)
The weather is very good
Today is Monday
Month is April
Year is 2020
t gave empty string because
the file pointer is at the end
>>> t=f.read(10) and the file is already read
>>> print(t) by read() function.
>>> f.close()
Made by Saurabh Arora
Reading from files
read function –
>>> f=open("abc.txt","r")
>>> a=f.read(15)
>>> a
'The weather is '
>>> b=f.read(20)
>>> b Note: \n is treated as 1 character
'very good\nToday is M'
Printing c variable by using print()
>>> c=f.read(25) >>> print(c)
onday
>>> c
Month is April
'onday\nMonth is April\nYear‘
Year'
>>> f.close()
Made by Saurabh Arora
Reading from files
2. readline function -
The readline() method reads only a single line from the file
and returns its contents in the form of a string.
>>> f=open("abc.txt","r")
>>> p=f.readline()
>>> p
'The weather is very good\n'
>>> q=f.readline()
>>> q
'Today is Monday\n'
>>> print(q)
Today is Monday
>>>
Made by Saurabh Arora
Reading from files
3. readlines function -
The readlines() method reads all the lines from the file and
returns its contents in the form of a list of string elements.
>>> f=open("abc.txt","r")
>>> L=f.readlines()
>>> L
['The weather is very good\n', 'Today is Monday\n', 'Month is April\n', 'Year is 2020']
>>> print(L)
['The weather is very good\n', 'Today is Monday\n', 'Month is April\n', 'Year is 2020']
>>> for i in L:
print(i)
Today is Monday
Month is April
Year is 2020
>>>
Made by Saurabh Arora
Split Function
Split function is applied on strings to break it into many parts. The
output is list of string elements.
>>> u="aman:101:12A"
>>> C=u.split(":")
>>> C
['aman', '101', '12A']
>>> print(L)
['Today', 'is', 'Monday', 'Date', 'is', '04-05-2020']
>>>
>>> f=open("xyz.txt","w")
>>> s="Today is Thursday"
>>> f.write(s)
17
>>> t="The Date is 30-04-2020"
>>> f.write(t)
22
>>> f.close()
>>>
>>> f=open("xyz.txt","w")
>>> L=["Computer Science Class\n","Today is Thursday\n","The Date is 30-04-2020"]
>>> f.writelines(L)
>>> f.close()
>>>
Question 2 : Write a function in python that reads a file and display all the
numbers or digits present in the file
def findlinesT(filename):
f=open(filename,"r")
L=f.readlines()
for i in L:
if i[0]=='T':
print(i)
findlinesT("abc.txt")
Output:
Today is Monday
Output:
Enter the name-harsh
['101:arjun:15000\n', '102:sonu:10000\n', '103:ram:25000\n', '104:harsh:20000']
['101', 'arjun', '15000\n']
['102', 'sonu', '10000\n']
['103', 'ram', '25000\n']
['104', 'harsh', '20000']
Salary is 20000 Made by Saurabh Arora
Ques. Write a function count_is() for counting the number of times “is” word occurs
inside the file
def count_is(str1):
f=open(str1,"r")
s=f.read()
L=s.split()
c=0
for i in L:
if i=="is":
c=c+1
print("Number of is = ",c)
f.close()
count_is("abc.txt")
Output:
Number of is = 4
def count_alphabets():
f=open("abc.txt","r")
s=f.read()
c=0
for i in s:
if i.isalpha():
c=c+1
print("Number of alphabets = ",c)
f.close()
count_alphabets()
Output:
Number of alphabets = 51
def findmax(filename):
f=open(filename,"r")
L=f.readlines()
big=L[0]
for i in L:
if len(big)<len(i):
big=i
print("Biggest line is ",big)
findmax("abc.txt")
Output:
Biggest line is The weather is very good
def remove_lowercase(filename1,filename2):
fr=open(filename1,"r")
fw=open(filename2,"w")
L=fr.readlines()
for i in L:
if not i[0].islower():
fw.write(i)
fr.close()
fw.close()
remove_lowercase("ex1.txt","ex2.txt")
Output:
>>> f=open("aug25.txt","w")
>>> f.write("Ravi Pandey")
11
>>> f.write("\nAman Kumar Jha")
15
>>> f.flush()
>>> f.write("\nShubham Kumar")
The data gets
14
written and saved
>>> f.flush()
into the file.
>>> f.close()
>>> f=open("aug25.txt","r")
>>> s=f.readline()
>>> s
'Ravi Pandey\n'
>>> print(s)
Ravi Pandey
>>> s=s.rstrip('\n')
>>> s
'Ravi Pandey'
The standard input, output and error device can also be used as
files by just importing sys module.
The with statement automatically closes the file after the block of
code gets over. So there is no need here to write f.close()
If an error occurs before the end of the block, the with statement
will handle it and will automatically close the file.
Binary files are easier and faster to read and write than text
files. In binary files there is no delimiter to a line. (‘\n’ was
used in text files for ending the line.)
Binary files are any files where the format isn't made up of
readable characters. Binary files can range from image files
like JPEGs or GIFs, audio files like MP3s or binary document
formats like Word or PDF.
try:
print(x)
except:
print("An error occurred")
The above code should give error as variable x does not exist, but try except helps to handle this
error means the error does not occurs.
Since the try block raises an error, the except block will be executed. Without the try block, the
program will crash and raise an error:
An error occurred
Made by
Saurabh Arora
seek() and tell() function
seek() function changes the position of the file pointer by placing
the file pointer at a specific position in the file.
f.seek (location)
f.seek (location, from_what)
rb opens a binary file for reading only. If the file does not exist,
then error occurs
r+ opens a text file for both reading and writing. If the file does
not exist, then error occurs
rb+ or r+b opens a binary file for both reading and writing. If
the file does not exist, then error occurs
wb+ or w+b opens a binary file for both writing and reading.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for writing and reading.
a+ opens a text file for both writing and reading. If file exists,
data is retained and new data being written will append to the
end. If the file does not exist, creates a new file for writing and
reading.
ab+ or a+b opens a binary file for both writing and reading. If
file exists, data is retained and new data being written will
append to the end. If the file does not exist, creates a new file
for reading and writing.
The comma delimits every value means the values are separated
with comma. The default delimiter is comma but newer versions
can have different delimiter character other than comma
Each line in a csv file is a data record. Each record consists of one
or more fields, separated by comma.
csv.reader
It is used for reading from CSV file. The csv.reader() function
returns a reader object and each row returned by the reader object
is a list of String elements
csv.writer
It is used for writing to CSV file. The csv.writer() function
returns a writer object that can be used to write into CSV files
using the writerow(), writerows() function
import csv
fw=open("student.csv","w")
w=csv.writer(fw)
w.writerow(['a','b','c'])
w.writerow(['x','y','z','w'])
w.writerow(['m','n','o','p'])
fw.close()
import csv
fw=open("student2.csv","w")
L=[['a','b','c'],['d','e','f'],['g','h','i'],['x','y','z']]
w=csv.writer(fw)
w.writerows(L)
fw.close()
import csv
fr=open("student.csv","r")
cr=csv.reader(fr)
for i in cr:
print(i)
Output:
['a', 'b', 'c'] The reason for the
empty lists are the
[] empty rows in CSV
['x', 'y', 'z', 'w'] file. The problem
can be solved by
[] using the newline
argument in open
['m', 'n', 'o', 'p']
function while
[] writing this CSV
File.
import csv
fw=open("student.csv","w",newline="")
w=csv.writer(fw)
w.writerow(['a','b','c'])
w.writerow(['x','y','z','w'])
w.writerow(['m','n','o','p'])
fw.close()
import csv
fr=open("student.csv","r")
cr=csv.reader(fr)
for i in cr:
print(i)
Output:
['a', 'b', 'c']
['x', 'y', 'z', 'w']
['m', 'n', 'o', 'p']
import csv
f=open("oct1.csv","w",newline="\r\n")
cw=csv.writer(f)
cw.writerow(['RollNo','Name','Marks'])
cw.writerow(['1','sanjay','60'])
cw.writerow(['2','abhimanyu','70'])
cw.writerow(['3','ravi','80'])
cw.writerow(['4','aman','90'])
f.close()
f=open("oct1.csv","a",newline="\r\n")
cw=csv.writer(f)
cw.writerow([5,'saket',100])
f.close()
Made by Saurabh Arora
Ques. Find the Number of Records in a CSV File
import csv
f=open("oct1.csv","r",newline="\r\n")
cr=csv.reader(f)
n=0
for i in cr:
if cr.line_num==1:
continue
n=n+1
print(n)
Output:
5
Output:
Enter the name to display record - aman
['4', 'aman', '90']