File Handling
Lecture 7
File Handling
• Allows the user to read, write, update, and
delete files.
• open() – to open a file and returns a file object
• read(), readline() – read content of the file
• write() – to write to an existing file
• close() – close the file
• delete() – delete files
• remove() – import os library – remove files
Open File
file = open("[Link]", "[r,a,w,x]")
• "r" – Read
– 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
Opening File
file = open("[Link]", "r")
# if the file is in the same folder as your .py
file = open("D:\\myfolder\[Link]",
"r")
# specify the path of file if in different folder
from your .py
print([Link]())
# by default, it reads the entire file content
print([Link](5))
# returns the first 5 characters in the file
[Link]()
Read a File
myfile = open("[Link]", "r")
print([Link]())
# reads the entire file
[Link]()
Reading a File
f = open("[Link]", "r")
print([Link]())
# reads one line
print([Link]())
for x in f:
print(x)
# reads the entire file by line
[Link]()
Write to a File
f = open("[Link]", "a")
[Link]("New Text")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]()
Writing to a File
f = open("[Link]", "a")
#appends content
[Link]("The file gets more content!")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]()
Overwriting
f = open("[Link]", "r+")
# write (overwrite existing) content
[Link]("I have deleted the content!")
print([Link]())
[Link]()
Remove a File
import os
[Link]("[Link]")
Deleting a File
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")