In this article you'll discover how to read and write to different types
of files using python.
Generally before diving into the method of writing and reading, we must begin
by opening the file according to what we want to do with it, we'll use
the built-in function open(), if you read the documentation you'll realise that it takes many argument
but our focus will be on the file and mode.In the file argument you must
specify the name of the file and the extension, for example if the name of my
file is HELLO WORLD and it is a text file, then the syntax in python would be
:
open(file = "HELLO WORLD.txt"), next we shall specify the mode of
opening, as we have many modes but we'll focus on the following :
- 'r' : open for reading
- 'w' : open for writing ( with this mode, we overwrite the file)
- 'a' : open for writing (with this mode, we don't overwrite the file)
- 'rb': open for reading binary
- 'wb': open for writing binary
and the syntax will look for example, like this : open(file='HELLO WORLD.txt',
mode= 'r')
after opening the file, now we'll begin be reading it, for this
we have three different methods :
- read() : it returns the entire file.
- readline(): it returns the first line of the file.
-
readlines(): it returns the entire file, line by line, in a list of
strings.
let's put this in practice using our python interpreter, I've put some
information in a text file, and I'll use the three methods to print it and see
the result :
using the read() method :
tape on the image if it is unclear to you
the output :
tape on the image if it is unclear to you
using the readline() method :
tape on the image if it is unclear to you
the output :
tape on the image if it is unclear to you
using the readlines() method :
tape on the image if it is unclear to you
the output :
tape on the image if it is unclear to you
that was for the reading part, for writing there are not a lot of methods to remember, but there is just one method : file.write(put here the things you want to overwrite or add to your file..)
for example, we are going to overwrite and add a text to our text file and see the difference :
writing with overwriting :
tape on the image if it is unclear to you
when looking in the output, we'll remark that
that character in file disappeared and we have just
"write" in the entire file.
writing without overwriting :
if we look in output, we'll remark that "write" is
added to what exists in the file
Buy Website Traffic
0 Comments