File Handling In Python
This blog covers the creating, reading, updating and deleting of files in python. Learning the handling files is as important as learning how to send requests in a web application.
The key function in file handling in python is the
function. It takes two arguments; the file name and the mode. The are four modes involved in file handling.
*
opens the file for reading and throws an error if the file doesn’t exist.
*
append mode creates file if file doesn’t exist, adds items to a file.
*
write mode, opens file for writing and creates the file if it does not exist.
*
creates the specified file, returns an error if the file exist.
in addition you can specify how the file can be handled, as a binary file or a text file…
*
text, this is the default value
*
binary mode, e.g., the handling of images and other binary files.
Syntax:
Opening a file for reading is actually enough to specify the name of the file,
the above is also same as writing:
This is basically obvious since the
and the
are the default values of the open method in file handling.
is just a variable to store the file, just as we store data types in python.
If we had the file “blog_file” containing the following
Hi there,
Figured you just named me blog_file… good choice of name by the way
use me responsibly 😅
The open function returns a file object named
in our case with access to the
method for accesssing the contets and can be displayed by:
To read only parts of the file, you can pass an argument with where you want to read, e.g.,
which would output “name by the way” it being the 3rd line.
Writing To an Existing File:
myfile.write("This is new line to give you company :) ")
When we use
instead of the
wee overide the contents of the file, this is serious {{The entire file 😠}}.
The other that I have not covered yet is creation using the
mode. This checks if the file created exists, if not then an empty file is created. Otherwise, an error is thrown.
Deleting a File 📥:
Deleting a file requires importation of the os module and thus deleting using the
method.
os.remove("unwanted_file.txt")
on the other hand you can delete a folder using
os.rmdir("unwanted_folder")
Another tip you can use to avoid errors is checking for conditions before actually deleting the file or opening a non existing one using the
funciton, this is one of the reasons as to why we get to encourage the use of the
mode for creating files, since it throws an error if the file exists 😜,
if os.path.exists("path_to_file_am_looking_for.txt"):
return "I liked the blog *.'"
else:
return "I still liked the blog *.'"
A clap a time does a
operation to the blog’s
variable 😉. Till next time 😃
Leave a Reply