Python Programming Notes-Unit - 2
Python Programming Notes-Unit - 2
File Handling
➢ The key function for working with files in Python is the open() function.
➢ The open() function takes two parameters; filename, and mode.
➢ "r" - Read - Default value. Opens a file for reading, error if the file does not exist
➢ "a" - Append - Opens a file for appending, creates the file if it does not exist
➢ "w" - Write - Opens a file for writing, creates the file if it does not exist
➢ "x" - Create - Creates the specified file, returns an error if the file exists
• In addition you can specify if the file should be handled as binary or text mode
Syntax
➢ To open a file for reading it is enough to specify the name of the file
➢ f = open("demofile.txt")
• Example
➢ By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
Read Lines
➢ Example
➢ Read one line of the file:
➢ f = open("demofile.txt", "r")
➢ print(f.readline())
• By calling readline() two times, you can read the two first lines
Example
Close Files
➢ It is a good practice to always close the file when you are done with it.
➢ Example
➢ Close the file when you are finish with it:
➢ f = open("demofile.txt", "r")
➢ print(f.readline())
➢ f.close()
Python File Write
• Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
• Example
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
• To create a new file in Python, use the open() method, with one of the following
parameters:
➢ "x" - Create - will create a file, returns an error if the file exist
➢ "a" - Append - will create a file if the specified file does not exist
➢ "w" - Write - will create a file if the specified file does not exist
• Example
• Example
Delete a File
➢ To delete a file, you must import the OS module, and run its os.remove() function:
• Example
➢ Remove the file "demofile.txt":
➢ import os
➢ os.remove("demofile.txt")
Delete Folder
• Example
➢ Remove the folder "myfolder":
➢ import os
➢ os.rmdir("myfolder")
Exception Handling
➢ When an error occurs, or exception as we call it, Python will normally stop and generate
an error message.
➢ The try block lets you test a block of code for errors.
➢ The else block lets you execute code when there is no error.
➢ The finally block lets you execute code, regardless of the result of the try- and
except blocks.
• Example
Else
➢ You can use the else keyword to define a block of code to be executed if no errors were
raised
Example
In this example, the try block does not generate any error
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
➢ The finally block, if specified, will be executed regardless if the try block raises an error or
not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")