Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
File handling & basic operation on file in python
1. Department of Computer Science & Engineering
SUBMITTED BY:
Ishant Jaiswal
2201920100146
CSE 2nd YEAR
SUBMITTED TO:
MR. MEGH SINGHAL
ASSISTANT PROFESSOR
CSE DEPARTMENT
FILE HANDLING IN PYTHON
2. What is file?
• Files are named locations on disk to information.
• They are used to store data permanently.
• Data is stored in non-volatile memory.
• We can retrieve data whenever
required.
3. Types of
file?
Text files:-
• Store data in the form of character. It is used
to store data and string. ex-txt file.
Binary files:-
• Store data in the form of bytes(group of 8
bits). ex-audio file,video file,pdf file.
4. What is file handling?
File handling means:-
• Opening a file.
• Performing some operations on it.
• Closing a file.
5. Opening file:-
Python provides an in built function open() to open file.
• file name:- file to be accessed.
• mode:- access mode (purpose of opening file).
• f :- file handler, file pointer.
• Syntax:-
f=open(file
name,mode=’r’,buffering,encoding=None,errors=None,newline=None,
closefd=True)
f=open(file name, mode=’r’)
6. Closing a file:-
•
• After performing operation, we have to close a file.
• Syntax:-
file_handler.close()
•
• close() :- function used to close a file.
7. Read data from file:-
T0 read content of file, we have following three methods:-
• read()
• readline()
• readlines()
8. Read data from file:-
read() :- This method is used to read data/content from a file
and return it as a string in text mode. it return bytes in binary
mode.
size:- It represent the number of character to be read in text
mode.
Syntax:-
file_object.read(size)
9. Read data from file:-
readline() :- This function is used to read a single line from a
file.
size:- It represent the number of character to read from line
Syntax:-
file_object.readline(size)
10. Read data from file:-
readlines() :- This function is used to read a all line from a
file and returns a list of lines.
Syntax:-
file_object.readlines()
11. Important Method:-
• tell() method
• seek() method
tell() :-
• This method is used to find the current position of a
file pointer from the beginning of the file.
• Position start from 0. It just like indexing in string.
Syntax:-
file_object.tell()
12. Important Method:-
seek() :-
• This method is used to change the position of file pointer.
• Remember file pointer position is always counted from
the beginning.
Syntax:-
file_object.seek(position)
14. Writing in a file:-
• In order to write data in file, we have to open in a mode
which provides the facility of writing data ex. w,a,x etc.
• W mode:-
• It opens the file to write only
• It overwrite the data in a file.
• If a file doesn’t exist, it creates a new file and write into it
• Mainly, two method are used for writing data in files
• write()
• writelines()
15. Writing in a file:-
• Syntax:-
file_object.write(data in string format)