You are on page 1of 9

Python Files and Functions

Python Functions
• A function is a block of organized, reusable
code that is used to perform a single, related
action (user defined)
• Syntax
def functionname(parameters):
"function_docstring"
function_suite
return [expression]
Function arguments

• Required arguments

def printme( str ):

print str

return

printme(‘Hello World’)
Function arguments

• Keyword arguments

def printinfo( name, age ):

print "Name: ", name

print "Age ", age

return;

printinfo( age=50, name="miki" )


Function arguments

• Default arguments

def printinfo( name, age = 35 ):

print "Name: ", name

print "Age ", age

return;

printinfo( age=50, name="miki" )

printinfo( name="miki" )
Function arguments
• Variable-length arguments

def printinfo( arg1, *vartuple ):

print "Output is: “

print arg1

for var in vartuple:

print var

return;

printinfo( 10 )

printinfo( 70, 60, 50 )


Python File Operations
• Open a file: f = open(“filename”, “mode”)

• Read a file: f.read()

• Write to a file: f.write(“argument”)


File Modes
Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation
fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)
File operations

You might also like