Steps to create data file in python
1. Opening a file
Before working with data files in Python, the first thing is to open the file. We can use open( ) function to do it as:
Syntax:
<file_object> = open(<filename>)
OR
<file_object> = open(<filename> , <mode>)
<file_object> is the file object used to read and write data to a file on disk. File object is used to obtain a reference to the file on disk and open it for different tasks.
<mode> is the file opening mode used to specify the operation we want to perform on file.
Different Modes to Open file are
‘r’ | Read only [File must exist otherwise I/O error is generated ] |
‘w’ | Write only
|
‘a’ | Append
|
‘r+’ | Read only
|
‘w+’ | Write and Read
|
‘a+’ | Write and Read
|
‘rb’ | Read only in binary mode
[File must exist otherwise I/O error is generated ] |
‘wb’ | Write only in binary mode
|
‘ab’ | Append in binary mode
|
‘rb+’ ‘r+b’ |
Read and Write in binary mode
|
‘wb+’
‘w+b’ |
Write and Read in binary mode
|
‘ab+’
‘a+b’ |
Write and Read in binary mode
|
Opening files in Read Mode
Example 1
file1 = open(“data.txt”)
OR
file1 = open(“data.txt”, "r")
Above statements open text file “data.txt” in read mode and attaches it to file object file1.
Example 2
file2 = open (“d:\\data.txt”)
OR
file2 = open (“d:\\data.txt”, “r”)
Above statements open text file “data.txt” stored in d: drive in read mode and attaches it to file object file2.
** We can also use single slash in the path but that may generate error as Python also provides escape sequences like \t, \n, \b etc.
Example 3
file3 = open (“d:\files\data.txt”)
OR
file3 = open (“d:\files\data.txt”, “r”)
Above statements open text file “data.txt” stored in d:\files folder in read mode and attaches it to file object file3.
** We can also use single slash in the path but that may generate error as Python also provides escape sequences like \t, \n, \b etc.
2. Reading or writing data in the file
We can write and read data from data files by using different predefined functions of Python. different functions to read and write data in Python are:
- write()
- read()
- readline()
3. Closing the file
We need to close file after performing required operations on it. Function fclose( ) can be used to close the file.
Syntax of fclose() function is:
<file_object>.close();
Example:
file1.close()