7 – File operations in Python

File operations in python have majorly three modes of operations. They are

  1. Write
  2. Read
  3. Append

WRITE OPERATION:

‘w’ is used to open the file in write mode. In write mode, the file pointer is set to the beginning of and so the file will be overwritten. The data available before will be deleted and the new data will be written. write() is used to write a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
f=open("t1.txt",'w')
f.write("Welcome to Python Programming in MYBTECHPROJECTS")
f.close()
 
#To write a file using with command
with open("t1.txt",'w') as f:
      f.write("Welcome to Python Programming in MYBTECHPROJECTS")
 
#To write a file line by line
l=[1,2,3,4,5,6,7,8,9]
with open("t1.txt",'w') as f:
     for i in l:
          f.write(str(i))
          f.write('\n')

READ OPERATION:

‘r’ is used to open the file in reading mode. In read mode, the file pointer is set to the beginning of the file and so it starts reading from first. Data can only be read and cannot be edited in read mode. read() is used to read a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
f=open("t1.txt",'r')
print (f.read())
f.close()
 
#To read a file using with
with open("t1.txt",'r') as f:
      print (f.read())
 
#To read a fileline by line    
with open("t1.txt") as f:
      for line in f:
            line=line.replace("\n","")
            print line

APPEND OPERATION:

‘a’ is used to open the file in append mode. In append mode the file pointer is set to the end of the file so the new data will be added to the file. 

1
2
3
4
5
6
7
f=open("t1.txt",'a')
f.write("Welcome to Python Programming in MYBTECHPROJECTS")
f.close()
 
#Append using with 
with open("t1.txt",'a') as f:
    f.write("Welcome to Python Programming in MYBTECHPROJECTS")

SEEK AND TELL OPERATIONS:

Seek() is used to return the current position of the file pointer. Tell(index) is used to read a specific position in the file.

1
2
3
4
5
6
7
8
9
10
f=open("t1.txt",'w')
 
print "File pointer position before writing",f.tell()
f.write("Welcome to Python Programming in MYBTECHPROJECTS")
print "File pointer position after writing",f.tell()
print "Moving position to 10 using f.seek(10)"
f.seek(10)
print "File pointer position after using seek(10)", f.tell()
 
f.close()

OUTPUT

1
2
3
4
5
6
>>> 
File pointer position before writing 0
File pointer position after writing 48
Moving position to 10 using f.seek(10)
File pointer position after using seek(10) 10
>>>
THANKYOU

 

SHARE THIS!!!

Gowtham S

Gowtham is a programming enthusiast. His field of interest includes Arduino, NodeMCU, Raspberry Pi, and Python. To know more about him visit https://mybtechprojects.tech/about-us/.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.