File Handling

It’s important and powerful feature of Python and it is widely used in Web application Where we can create, edit, delete and update the file in run time.

The main functions used in File Handling are open

There are basically four different modes for opening file:

“r” (read) This mode is used for reading the file.
“a” (append) This mode is used for inserting data into existing files.
“w”(write) This mode is used for writing something on file.
“x”(exclusive) This mode is used for create new file but raised failed if file already exists
“+”(advance) It gives advance feature to exist mode
“t” (text) Default value is Text mode
“b”(binary) Binary mode

Syntax

f=open(“example.txt”,”mode”)

Program for Create file

f=open("demo.txt","w")
f.write("Hello How Are You ?")#write something
print("File Successfully Create")
f.close()#closing file

Output

File Successfully Create

Program for ReadFile

f=open("demo.txt","r")
print(f.read())
f.close()

Output

Hello How Are You ?

Program for Append or Update(if we used ‘w’ mode then old file demo.txt will replace with new one)

f=open("demo.txt","a")
f.write(" Using append mode ")
print("file append successfully")
f.close()

Output

file append successfully

Program for Read Append File

f=open("demo.txt","r")
print(f.read())
f.close()

Output

Hello How Are You ? Now I am using Append Mode 

Program for Exclusive

f=open("demo.txt","x")
f.write("x mode")

If we create an existing file.

Output

Traceback (most recent call last):
  File "C:/Users/laptop/Desktop/hello.py", line 1, in 
    f=open("demo.txt","x")
FileExistsError: [Errno 17] File exists: 'demo.txt'

Program with rectify

f=open("demo1.txt","x")
f.write("x mode")
print("successfully create")

Output

successfully create

Let’s start with Advance mode(+)

+ used postfix with exist mode to enhance facility of another

r+ Read+Write
w+ Write+Read
a+ Append+Read
x+ Create+Read

Here we are describe two function are used with Advance mode

seek(argument) This function is used to adjust the cursor position.
tell() This is used for know the current position of the cursor.

Program with Advance Mode

f=open("demo.txt","w+")
f.write("I am creating file and write something")
print("Current Position",f.tell())
print("After used seek",f.seek(0))
print(f.read())
f.close()

Output

Current Position 38
After used seek 0
I am creating file and write something
Subscribe Now