SlideShare una empresa de Scribd logo
1 de 20
FUNCTIONS AND FILE HANDLING
IN
PYTHON
SANTOSH VERMA
Faculty Development Program: Python Programming
JK Lakshmipat University, Jaipur
(3-7, June 2019)
Functions in Python
 A function is a set of statements that do some specific
computation and produces output.
 The idea is to put some commonly or repeatedly done task
together and make a function, so that instead of writing the
same code again and again for different inputs, we can call
the function. Reusability.
 Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are called
user-defined functions.
 Minimum error propagation due to reusability.
 Syntax of the function:
def function_name(list of formal parameters)
Body_of_the_function
return
For example:
def maxVal(x, y):
if x>y:
return x
else:
return y
 Function call/invocation syntax:
maxVal(3,4)
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Driver code
evenOdd(2)
evenOdd(3)
Pass by Reference or pass by value?
 One important thing to note is, in Python every variable
name is a reference.
 When we pass a variable to a function, a new reference to
the object is created.
 Parameter passing in Python is same as reference passing in
Java.
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to
something else, the connection between passed and received
parameter is broken.
def myFun(x):
x = [20, 30, 40]
# Driver code
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)
Output:[10, 11, 12, 13, 14, 15]
Default Arguments
 A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Output:
('x: ', 10)
('y: ', 50)
Like C++ default arguments,
any number of arguments in a
function can have a default
value. But once we have a
default argument, all the
arguments to its right must also
have default values.
Keyword arguments:
 The idea is to allow caller to specify argument name with
values so that caller does not need to remember order of
parameters.
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname =‘Santosh', lastname =‘verma')
student(lastname =‘verma', firstname =‘Santosh')
Variable number of arguments:
 We can have both normal and keyword variable number of
arguments.
def myFun(*args):
for arg in args:
print (arg)
myFun(“FDP”, “on”, “Python”,
“Programming”)
Output:
FDP
on
Python
Programming
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first =‘santosh', mid =‘kumar',
last=‘verma’)
Output:
last == verma
mid == kumar
first == santosh
Anonymous functions/ Lambda
Abstraction
 Anonymous function means that a function is without a name.
 As we already know that def keyword is used to define the normal
functions
 While, the lambda keyword is used to create anonymous functions. A lambda
function can take any number of arguments, but can only have one
expression.
cube = lambda x: x*x*x
print(cube(7))
Output: 343
Note: It is as similar as inline functions in other programming language.
x = lambda a : a + 10
print(x(5))
Output: 15
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Output: 13
Recursion
 Recursion is nothing but calling a function directly or in-
directly, and must terminate on a base criteria.
def factI(n):
‘’’Assumes n an int > 0
returns n!’’’
result = 1
while n>1:
result = result * n
n - = 1
return result
def factR(n):
‘’’Assumes n an int > 0
returns n!’’’
if n ==1:
return n
else:
return n*factR(n-1)
File Handling
 Deals with long term persistence of the data. Like other programming languages,
python to supports file handling.
 Python allows users to handle files i.e., to read and write files, along with many
other file handling options, to operate on files.
 As compare to other programming language, python file handling is simple
and need not to import anything.
 Each line of code includes a sequence of characters and they form text file. Each
line of a file is terminated with a special character, called the EOL or End of Line
characters. It ends the current line and tells the interpreter a new one has begun.
 File handling is an important part of any web application.
The open Function
 file object = open(file_name , access_mode, buffering)
 file_name − name of the file that is required to be accessed.
 access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append.
 buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the indicated
buffer size. If negative, the buffer size is the system default(default behavior). Optional
File Modes
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
W+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
The file Object Attributes
OPEN FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
READ FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print every line one by one in the file
print (file.read())
READ FIRST ‘N’ CHAR from FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print first five characters in the file
print (file.read(5))
Creating a file using write() mode
file = open('C:Userssantosh_homeDesktopfdp.txt', ‘w’)
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Working of append() mode
file = open('C:Userssantosh_homeDesktopfdp.txt’, ‘a’)
file.write("This will add this line")
file.close()
Using write along with with() function
# Python code to illustrate with() alongwith write()
with open("C:Userssantosh_homeDesktopfdp.txt", "w") as f:
f.write("Hello World!!!")
split() using file handling
# Python code to illustrate split() function
with open("C:Userssantosh_homeDesktopfdp.txt", “r") as file:
data = file.readlines()
for line in data:
word = line.split()
print word
Thank You!

Más contenido relacionado

La actualidad más candente

4. python functions
4. python   functions4. python   functions
4. python functions
in4400
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
AtreyiB
 

La actualidad más candente (20)

File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Python - Lecture 8
Python - Lecture 8Python - Lecture 8
Python - Lecture 8
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python basics
Python basicsPython basics
Python basics
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Day3
Day3Day3
Day3
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 
Day2
Day2Day2
Day2
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Basics
Python BasicsPython Basics
Python Basics
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Python
PythonPython
Python
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 

Similar a Functions in python

FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
Muhammed Thanveer M
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
Nimrita Koul
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 

Similar a Functions in python (20)

Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
Unit VI
Unit VI Unit VI
Unit VI
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
Python advance
Python advancePython advance
Python advance
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Workshop presentation hands on r programming
Workshop presentation hands on r programmingWorkshop presentation hands on r programming
Workshop presentation hands on r programming
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Satz1
Satz1Satz1
Satz1
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Unit5
Unit5Unit5
Unit5
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 

Más de Santosh Verma

Más de Santosh Verma (9)

Migrating localhost to server
Migrating localhost to serverMigrating localhost to server
Migrating localhost to server
 
Wordpress tutorial
Wordpress tutorialWordpress tutorial
Wordpress tutorial
 
Sorting tech comparision
Sorting tech comparisionSorting tech comparision
Sorting tech comparision
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Access modifiers in Python
Access modifiers in PythonAccess modifiers in Python
Access modifiers in Python
 
SoC: System On Chip
SoC: System On ChipSoC: System On Chip
SoC: System On Chip
 
Embedded system design using arduino
Embedded system design using arduinoEmbedded system design using arduino
Embedded system design using arduino
 
Snapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 ArchitectureSnapdragon SoC and ARMv7 Architecture
Snapdragon SoC and ARMv7 Architecture
 
Trends and innovations in Embedded System Education
Trends and innovations in Embedded System EducationTrends and innovations in Embedded System Education
Trends and innovations in Embedded System Education
 

Último

Último (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 

Functions in python

  • 1. FUNCTIONS AND FILE HANDLING IN PYTHON SANTOSH VERMA Faculty Development Program: Python Programming JK Lakshmipat University, Jaipur (3-7, June 2019)
  • 2. Functions in Python  A function is a set of statements that do some specific computation and produces output.  The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can call the function. Reusability.  Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are called user-defined functions.  Minimum error propagation due to reusability.
  • 3.  Syntax of the function: def function_name(list of formal parameters) Body_of_the_function return For example: def maxVal(x, y): if x>y: return x else: return y  Function call/invocation syntax: maxVal(3,4)
  • 4. # A simple Python function to check # whether x is even or odd def evenOdd( x ): if (x % 2 == 0): print "even" else: print "odd" # Driver code evenOdd(2) evenOdd(3)
  • 5. Pass by Reference or pass by value?  One important thing to note is, in Python every variable name is a reference.  When we pass a variable to a function, a new reference to the object is created.  Parameter passing in Python is same as reference passing in Java.
  • 6. # Here x is a new reference to same list lst def myFun(x): x[0] = 20 # Driver Code (Note that lst is modified # after function call. lst = [10, 11, 12, 13, 14, 15] myFun(lst) print(lst) Output: [20, 11, 12, 13, 14, 15]
  • 7. When we pass a reference and change the received reference to something else, the connection between passed and received parameter is broken. def myFun(x): x = [20, 30, 40] # Driver code lst = [10, 11, 12, 13, 14, 15] myFun(lst); print(lst) Output:[10, 11, 12, 13, 14, 15]
  • 8. Default Arguments  A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument. def myFun(x, y=50): print("x: ", x) print("y: ", y) # Driver code (We call myFun() with only # argument) myFun(10) Output: ('x: ', 10) ('y: ', 50) Like C++ default arguments, any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values.
  • 9. Keyword arguments:  The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters. def student(firstname, lastname): print(firstname, lastname) # Keyword arguments student(firstname =‘Santosh', lastname =‘verma') student(lastname =‘verma', firstname =‘Santosh')
  • 10. Variable number of arguments:  We can have both normal and keyword variable number of arguments. def myFun(*args): for arg in args: print (arg) myFun(“FDP”, “on”, “Python”, “Programming”) Output: FDP on Python Programming def myFun(**kwargs): for key, value in kwargs.items(): print ("%s == %s" %(key, value)) # Driver code myFun(first =‘santosh', mid =‘kumar', last=‘verma’) Output: last == verma mid == kumar first == santosh
  • 11. Anonymous functions/ Lambda Abstraction  Anonymous function means that a function is without a name.  As we already know that def keyword is used to define the normal functions  While, the lambda keyword is used to create anonymous functions. A lambda function can take any number of arguments, but can only have one expression. cube = lambda x: x*x*x print(cube(7)) Output: 343 Note: It is as similar as inline functions in other programming language. x = lambda a : a + 10 print(x(5)) Output: 15 x = lambda a, b, c : a + b + c print(x(5, 6, 2)) Output: 13
  • 12. Recursion  Recursion is nothing but calling a function directly or in- directly, and must terminate on a base criteria. def factI(n): ‘’’Assumes n an int > 0 returns n!’’’ result = 1 while n>1: result = result * n n - = 1 return result def factR(n): ‘’’Assumes n an int > 0 returns n!’’’ if n ==1: return n else: return n*factR(n-1)
  • 13. File Handling  Deals with long term persistence of the data. Like other programming languages, python to supports file handling.  Python allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.  As compare to other programming language, python file handling is simple and need not to import anything.  Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters. It ends the current line and tells the interpreter a new one has begun.  File handling is an important part of any web application.
  • 14. The open Function  file object = open(file_name , access_mode, buffering)  file_name − name of the file that is required to be accessed.  access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append.  buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior). Optional
  • 15. File Modes Modes Description r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. W+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
  • 16. The file Object Attributes
  • 17. OPEN FILE file = open('C:Userssantosh_homeDesktopfdp.txt', 'r') # This will print every line one by one in the file for each in file: print (each) READ FILE file = open('C:Userssantosh_homeDesktopfdp.txt', 'r') # This will print every line one by one in the file print (file.read()) READ FIRST ‘N’ CHAR from FILE file = open('C:Userssantosh_homeDesktopfdp.txt', 'r') # This will print first five characters in the file print (file.read(5))
  • 18. Creating a file using write() mode file = open('C:Userssantosh_homeDesktopfdp.txt', ‘w’) file.write("This is the write command") file.write("It allows us to write in a particular file") file.close() Working of append() mode file = open('C:Userssantosh_homeDesktopfdp.txt’, ‘a’) file.write("This will add this line") file.close()
  • 19. Using write along with with() function # Python code to illustrate with() alongwith write() with open("C:Userssantosh_homeDesktopfdp.txt", "w") as f: f.write("Hello World!!!") split() using file handling # Python code to illustrate split() function with open("C:Userssantosh_homeDesktopfdp.txt", “r") as file: data = file.readlines() for line in data: word = line.split() print word