PREV NEXT
Till now we are used variables to store the data,but the data which ever stored in variables it will not available once the application end.To achieve this we are going to use the file concept.
In python we can handling the file based on three components.They are
1.Open File
2.Process the file (wirite and read operations)
3.Close file
Types of Files:
As we known two types of files are available.They are
1. Text Files
2. Binary Files
1. Text File:
A text file is nothing but which is containing alphabates,numbers,symbols,no specific formatings it is called Text file
2. Binary File:
- A Binary file is nothing but a file is stored in binary format which is not readable by human beings except machines this are called binary file
- In This tutorial we can work both files but before that we are going to discuss about it ,it should what are the mode have to perform operation on the files.
Mode | Explanation |
‘w’
|
It will opens the file for writing the data,if file is not found then it will create new file and then it will write
|
‘r’
|
It will open the file for reading ,if file not found it will returns FileNotFoundError error.
|
‘a’
|
It will opens the file for append mode ,if file is not found then it will create new file and then it will write,if found it append the data into that file
|
‘w+’
|
It will opens the file for writing and reading the data,if file is not found then it will create new file and then it will write
|
‘r+’
|
It will open the file for writing and reading ,if file not found it will returns FileNotFoundError error.
|
‘a+’
|
It will opens the file for reading and append mode ,if file is not found then it will create new file and then it will write,if found it append the data into that file
|
‘wb’
|
It will opens the file for writing the data in binary format,if file is not found then it will create new file and then it will write
|
‘rb’
|
It will open the file for reading binary ,if file not found it will returns FileNotFoundError error.
|
‘ab’
|
It will opens the file for append mode binary format ,if file is not found then it will create new file and then it will write,if found it append the data into that file
|
‘wb+’
|
It will opens the file for writing and reading the data in binary format,if file is not found then it will create new file and then it will write
|
‘rb+’
|
It will open the file for writing and reading in binary format ,if file not found it will returns FileNotFoundError error.
|
‘ab+’
|
It will opens the file for read and append mode binary format ,if file is not found then it will create new file and then it will write,if found it append the data into that file
|
Methods for file operations:
Method
|
Explanation |
read(num_arg)
|
It will read the number of characters which number passed as an argument ,it will return as a string
|
write(str_arg)
|
It can write the string argument to the file and then it will return no.of character to the file
|
readline()
|
read a single line ,returns it as a string
|
readlines()
|
read the content line by line read them as collection strings
|
close()
|
close the file
|
tell()
|
returns the current position of file pointer
|
seek(offset,origin)
|
Moves the file pointer to given offset from the origin
|
1. Open A File:
To perform read or write etc any kind of operation we need to open the file by using the in built fucntion open.This will retrun a file object,by using this object we can perform the required operation
Syntax:
object=open(file_name,mode,buffering)
file_name:
It is a file name representing in string format
mode:
This is the only actual parameter to open the file in which i.e read,write etc.By default file will be open in read mode
buffering:
The default value is “0”,means buffering will not take place.If the value is “1” then buffering will take place .If more than “1” buffering will take with respect to buffer size.If negative ,then it will consider default operation.
Example 1:
Script for understanding how to open file and known the attributes of that file
1 2 3 4 5 6 7 8 9 |
file_obj = open("sample.txt") print ("File name: ", file_obj.name) print ("File state: ", file_obj.closed) print ("Opening mode: ", file_obj.mode) print ("Softspace flag: ", file_obj.softspace) |
Output:
1 2 3 4 5 6 7 |
File name: sample.txt File state: False Opening mode: r Softspace flag: 0 |
Example 2:
How to read entire data in file
1 2 3 |
file_obj = open("sample.txt") print(file_obj.read()) |
Output:
1 2 3 4 5 |
Hello,python is great and good programming language so it very good to learn |
Example 3:
How to close a file
1 2 3 4 5 |
file_obj = open("sample.txt") file_obj.close() print(file_obj.read()) |
Output:
1 2 3 4 5 6 7 |
Traceback (most recent call last): File "file2.py", line 3, in <module> print(file_obj.read()) ValueError: I/O operation on closed file. |
Using with exception and close file
try:
1 2 3 4 5 6 7 |
file_obj = open("sample.txt") finally: file_obj.close() print(file_obj.read()) |
Output:
1 2 3 4 5 6 7 |
Traceback (most recent call last): File "file3.py", line 5, in <module> print(file_obj.read()) ValueError: I/O operation on closed file. |
Example 4:
How to write into file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
f=open('file.txt', 'w')#encoding = 'utf-8') f.write('Hello world\n') f.write('Hi how are you\n') f.write('fine whats going on\n') f= open('file.txt', 'r') content = f.readlines() for line in content: print(line) |
Output:
1 2 3 4 5 |
Hello world Hi how are you fine whats going on |
Example5:
How to read a file:
1 2 3 4 5 |
f=open('file.txt', 'r') print(f.read(20)) print(f.read()) |
Output:
1 2 3 4 5 6 7 |
Hello world Hi how a re you fine whats going on |
Example 6:
How rad the offset and cheange the offset
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
f=open('file.txt', 'r') data = f.read(12); print('String is : ', data) position = f.tell(); print('Current file position : ', position) position = f.seek(0, 0); data = f.read(); print('String is : ', data) f.close() |
Output:
1 2 3 4 5 6 7 8 9 |
String is : Hello world Current file position : 12 String is : Hello world Hi how are you fine whats going on |
Example 7:
How to rename and delete the file
1 2 3 4 5 |
Rename a file import os os.rename( "file.txt", "new_file.txt" ) #os.rename(old_file,renam_file) |
Output:
1 |
It will rename the file |
Delete the file:
import os
os.remove( “new_file.txt” )
Output:
1 |
It will delete the file |
Example 8:
File operations by suing with clause
1 2 3 4 5 6 7 8 9 10 11 12 13 |
with open('file.txt', 'w') as f: f.write('my first file\n') f.write('This file\n') f.write('contains three lines\n') with open('file.txt', 'r') as f: data=f.read() print (data) |
Output:
1 2 3 4 5 |
my first file This file contains three lines |
Example 9:
File with exception handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import os filename = input("Enter file name: ") try: f = open(filename, "r") for line in f: print(line, end="") f.close() except FileNotFoundError: print("File not found") except PermissionError: print("don't have the permission to read the file") except FileExistsError: print("don't have the permission to read the file") except: print("Unexpected error while reading the file") else: print("Program runned without any problem") finally: print("finally: This will always execute") |
Iteration1:
Input1:
1 2 3 |
give the existing file name ex:file.txt Enter file name: file.txt |
Output:
1 2 3 4 5 6 7 8 9 |
my first file This file contains three lines Program runned without any problem finally: This will always execute |
Iteration2:
Input1:
give the existing file name ex:file.txt
Enter file name: file1.txt
Output:
1 2 3 |
File not found finally: This will always execute |