Properties of File Object:
A file object or file handle is the reference of a file which helps to do various task on file. It has various
properties like:
1. name : It displays the name of the file
2. mode : It displays the mode of file(in which mode it is opened)
3. closed : It displays whether the file is closed or not. It return False if the file is open
and True if the file is closed.
4. readable() : It displays whether the file is readable or not.
for example:
f=open(“Data.txt”,”w”)
print(f.name)
print(f.mode)
print(f.closed)
print(f.readable())
Output of the above program will be
data.txt
False
False
Read() method:
(From book summary part read(n) and readline(n), readlines())
Functions for Reading File:
Reading file help us to play with the character, word or lines of a file. There are many methods or
functions in python which help us to read data from file. We will discuss one by one
1. read() : This function is used to read the entire content of file.
for example:
f = open("data.txt", "r")
d = f.read( )
The first line of code will open the file data.txt in read mode and the second line will read
the entire content and transfer/store data in variable d in the form of String.
2. read(n) : This function will read the first n character from the file .
for example:
f = open("data.txt", "r")
d = f.read(5)
The above code will print the first five character from the file.
3. readline() : This function will read one line at a time from the file.
Syntax of using readline() is
f = open("data.txt", "r")
d = f.readline()
print(d)
The above code will read and print first line from the file. To read the entire content of file, we
need to use the loop.
f = open("data.txt", "r")
for i in f:
print(i)
3. readlines() : This function is used to read all the lines from the file. This method will return a
list of strings, each separated by \n.
f = open("data.txt", "r")
d = f.readlines()
print(d)
Writing to File:
(From book summary part write() and writelines() )
We can write data into our file with the help of programs in python. When we open file in write mode
and file does not exist then this mode will create a new file.
There are two functions in python which help us to write data into a file.
1. write(string) : This method takes a string as parameter and write the same string into our file. This
method does not add EOL (End of Line) character automatically. We have to add ‘\n’ character after
each line. This method takes only string as argument so if you want to add numbers in file then first we
need to convert the number into string.
f = open("data.txt", "w")
f.write("welcome to my site")
f.write("csiplearninghub.com")
f.close()
Output of the above code:
Text File:
Welcome to my site csiplearninghub.com
NOTE : Don’t Forget to write the close() method at the end of the code
To display the above text in separate lines we need to add “\n” at the end of first line.
f = open("data.txt", "w")
f.write("welcome to my site\n")
f.write("csiplearninghub.com")
f.close()
Output of above code:
Text File:
welcome to my site
csiplearninghub.com
2. writelines() : This method is used for writing the sequence data type like list, tuple or string into a
file.
Syntax of writelines()
f.writelines(sequence)
Point to remember : When we have to write a list, tuple we will use writelines() instead of write(). For
string, we can use any function either write() or writelines().
With Statement:
Till now we have done many programs and in each programs we have used the following functions.
i) open()
ii) close()
we can close the file without using close() function or we can say that file automatically closed and that
can be achieved by using “with” statement.
Demonstration of “with” Statement in the following program
with open("data.txt", "w") as f:
f.write("Welcome to\n")
f.write("my website\n")
f.write("www.csiplearninghub.com")
In the above program we have not called the close() function, the file will automatically closed.
Appending to File:
When we want to add more data into a file which already contains some data then we use this append
mode. When we open the file in append mode then the following thing happens
1. It opens the file with file pointer at the end of the file.
2. If the file does not exist then this mode create a new blank file with pointer in the beginning.
NOTE: In simple words we can understand that append means adding data to a file without erasing
the existing content.
Syntax of opening file in append mode:
f = open("data.txt", "a")
The above code will open a file “data.txt” in append mode with ‘f’ as a file handle/object. Understand
the concept of Append:
Step 1: Open a file and write something
f = open("data.txt")
f.write("Welcome to my site\n")
f.write("csiplearninghub.com\n")
f.close()
Output of above program:
Text File:
Welcome to my site
csiplearninghub.com
Step 2 : Open a file to add some more data to the above file.
f = open("data.txt", "a")
f.write("File Handling handout part - 1\n")
f.write("File Handling handout part - 2\n")
f.close()
Output of above program:
Text File:
Welcome to my site
csiplearninghub.com
File Handling handout part – 1
File Handling handout part – 2
NOTE : In above code when we open file in append mode, it did not erase the existing content and ,
moreover, added the new content at the end of file.
Binary File in Python
What is Binary File ?
Binary Files are not in human readable format. It can be read by using some special tool or program.
Binary files may be any of the image format like jpeg or gif.
Why Binary File in Python?
When ever we want to write a sequence like List or Dictionary to a file then we required binary file in
python.
Steps to work with Binary File in Python
1. import pickle module.
2. Open File in required mode (read, write or append).
3. Write statements to do operations like reading, writing or appending data.
4. Close the binary file
How to write data in Binary File?
Python provides a module named pickle which help us to read and write binary file in python.
Remember : Before writing to binary file the structure (list or dictionary) needs to be converted in
binary format. This process of conversion is called Pickling. Reverse process Unpickling happen
during reading binary file which converts the binary format back to readable form.
Program:
Line wise explanation of the above code :
1. Line one is just to define our function.
2. In line 2 we are importing a module pickle which help to read and write data to binary file.
3. In line number 3, we are opening a file named “data.dat” in writing mode and ‘f’ is our file
object/handle.
4. Line number 4, we are declaring a list which needs to be write in a file.
5. This line is doing the main role of writing in a file. dump function of pickle module is used to
write list in binary file.
6. This line is simply closing the file.
7. Last line is to calling function bwrite()
Output:
NOTE : Above is the binary file “data.dat” which is not in human readable format.
How to read data in Binary File?
Python provides a module named pickle which help us to read binary file in python.
Python CSV File Handling
CSV (Comma-separated values) is a common data exchange format used by the
applications to produce and consume data.
A CSV file is a simple text file where each line contains a list of values (or fields)
delimited by commas (mostly), but you will encounter CSV files where data is delimited
using tab (\t) or pipe (|) or any other character.
The first line of the CSV file represents the header containing a list of column names in
the file.
CSV file is commonly used to represent tabular data.
See the following table
Python CSV File
The above table will be stored in CSV format as follows:
If the values in the table contain comma(,) like below in column Address
Then in CSV it will be stored like below (Values containing comma will be enclosed in double quotes)
Python Provides CSV module to work with csv file:
Main Functions are:
1. reader()
2. writer()
3. DictReader()
4. DictWriter()
1. reader() function : This function help us to read the csv file. This function takes a file object
and returns a _csv.reader object that can be used to iterate over the contents of a CSV file.
How to read entire data from data.csv file?
Let we try to read the following file ie “data.csv”
data.csv
Python CSV File
Line-wise explanation of the code
1. The first line is importing a csv module.
2. This line is opening a file (data.csv) in reading mode and f is file object or file handle.
3. This line is returning a csv.reader object that can be used to iterate over csv file contents
4. We are using loop on the object which is returned by the previous line
Python CSV File
How to read specific column from data.csv?
Python CSV Files: