DEV Community

Arokya Naresh
Arokya Naresh

Posted on

File Handling in Python

File Handling in Python
Modes
Read Mode 'r'
Write Mode 'w'
Append(Editable) 'a'
to read binary file 'rb'
To delete a file use remove()

To open a source file in readmode

Eg;
with open('source.txt','r') as file:

print(file,type(file))

To get to know the type of the file
with open('source.txt','r') as file:
print(file,type(file))

To create a new file or over-write use Write mode

Eg:
with open('source1.txt','w') as file:
file.write('e f g h')
file.write('i j k l')

To append more info we use append mode

Eg:
with open('source1.txt','a') as file:
file.write('m n o p')

saved file will be
e f g hi j k lm n o p

To check whether file present or not
import os

if os.path.isfile('source1.txt'):
print('source1 founded')
else:
print('source1 not founded')

o/p:
source1 founded

Again to read the content of that file

with open('source1.txt','r') as source_file:
content=source_file.readline()
print(content)

o/p

e f g hi j k lm n o p

To read binary file 'rb'
with open('binary.txt','rb') as source_file:

To delete a file

import os
os.remove('source1.txt')

Top comments (0)