16 file handling in python
1. Using file handling we can do file operations
# How to open a file in python ?
1. We can open a file two ways in python
1. open()
2. With open()
# OPEN
1. Using open we can open only one file at a time and we have to close a file explicity
# WITH OPEN
1. Using with open we can open multiple files at a time and no need to close files explicity
# File Open Modes In Python
r ==> It opens a file for read only.
w ==> It allows write-level access to a file. If the file already exists, then it’ll get overwritten. It’ll create a new file if the same doesn’t exist.
a ==> It opens the file in append mode.
a+ ==> It opens a file FOR append AND read
rb ==> It opens a binary file for read
1) Read file
fh = open('names.txt', 'r')
## To open a file from another path
#fw = open(r'C:\Users\smellamput001\Desktop\BACKUP_EPRO\RRR.txt', 'r')
## Using read we can read entire file data and return in string format
fdata = fh.read()
print(fdata)
## To read the first five characters
#fdata = fh.read(5)
#print(fdata)
## Using readline we can read only one line and return in string format
#line = fh.readline()
#print(' 1 ', line)
#line = fh.readline()
#print(' 2 ', line)
## Using readlines we can read total lines in a file and return in list format
lines = fh.readlines()
print(' READ LINES ', lines)
# To close a file
fh.close()
5 ) tell( function
'''
1. Tell is used to find the file handler position
'''
fh = open('names.txt')
# To know File handler position before read any data
print(' Before read :', fh.tell())
# Using readline we can read only one line and return in string format
line = fh.readline()
# To know File handler position after read a line
print(' After read :', fh.tell())
# To close a file
fh.close()
Comments
Post a Comment