Open Function: File - Object Open ("Filename", "Mode") Where File - Object Is The Variable To Add The
Open Function: File - Object Open ("Filename", "Mode") Where File - Object Is The Variable To Add The
html
Open ( ) Function
In order to open a file for writing or use in Python, you must rely on the built-in open ()
function.
As explained above, open ( ) will return a file object, so it is most commonly used with
two arguments.
An argument is nothing more than a value that has been provided to a function, which is
relayed when you call it. So, for instance, if we declare the name of a file as “Test File,”
that name would be considered an argument.
The syntax to open a file object in Python is:
file_object = open(“filename”, “mode”) where file_object is the variable to add the
file object.
The second argument you see – mode – tells the interpreter and developer which way
the file will be used.
Mode
Including a mode argument is optional because a default value of ‘r’ will be assumed if it
is omitted. The ‘r’ value stands for read mode, which is just one of many.
The modes are:
● ‘r’ – Read mode which is used when the file is only being read
● ‘w’ – Write mode which is used to edit and write new information to the file (any
existing files with the same name will be erased when this mode is activated)
● ‘a’ – Appending mode, which is used to add new data to the end of the file; that is
new information is automatically amended to the end
● ‘r+’ – Special read and write mode, which is used to handle both actions when
working with a file
So, let’s take a look at a quick example.
F = open(“workfile”,”w”)
Print f
This snippet opens the file named “workfile” in writing mode so that we can make
changes to it. The current information stored within the file is also displayed – or printed
– for us to view.
Once this has been done, you can move on to call the objects functions. The two most
common functions are read and write.
To get more familiar with text files in Python, let’s create our own and do some
additional exercises.
Using a simple text editor, let’s create a file. You can name it anything you like, and it’s
better to use something you’ll identify with.
For the purpose of this tutorial, however, we are going to call it “testfile.txt”.
Just create the file and leave it blank.
To manipulate the file, write the following in your Python environment (you can copy and
paste if you’d like):
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
Naturally, if you open the text file – or look at it – using Python you will see only the text
we told the interpreter to add.
$ cat testfile.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can.
There are actually a number of ways to read a text file in Python, not just one.
If you need to extract a string that contains all characters in the file, you can use the
following method:
file.read()
The full code to work with this method will look something like this:
For example, with the following code the interpreter will read the first five characters of
stored data and return it as a string:
print (file.read(5))
Notice how we’re using the same file.read() method, only this time we specify the
number of characters to process?
The output for this will look like:
Hello
If you want to read a file line by line – as opposed to pulling the content of the entire file
at once – then you use the readline() function.
Each time you run the method, it will return a string of characters that contains a single
line of information from the file.
Hello World
If we wanted to return only the third line in the file, we would use this:
But what if we wanted to return every line in the file, properly separated? You would use
the same function, only in a new form. This is called the file.readlines() function.
[‘Hello World’, ‘This is our new text file’, ‘and this is another line.’, ‘Why? Because
we can.’]
Notice how each line is separated accordingly? Note that this is not the ideal way to
show users the content in a file. But it’s great when you want to collect information
quickly for personal use during development or recall.
Hello World
This is our new text file
and this is another line.
Why? Because we can.
One thing you’ll notice about the file write method is that it only requires a single
parameter, which is the string you want to be written.
This method is used to add information or content to an existing file. To start a new line
after you write data to the file, you can add an EOL character.
file.write(“This is a test”)
file.write(“To add more lines.”)
file.close()
Obviously, this will amend our current file to include the two new lines of text. There’s no
need to show output.
Closing a File
When you’re done working, you can use the fh.close() command to end things. What
this does is close the file completely, terminating resources in use, in turn freeing them
up for the system to deploy elsewhere.
It’s important to understand that when you use the fh.close() method, any further
attempts to use the file object will fail.
Notice how we have used this in several of our examples to end interaction with a file?
This is good practice.
To help you better understand some of the methods discussed here, we’re going to
offer a few examples of them being used in the real world. Feel free to copy the code
and try it out for yourself in a Python interpreter (make sure you have any named files
created and accessible first).
Opening a text file:
fh = open(“hello.txt”, “r”)
Fh = open(“hello.txt”, “r”)
print fh.read()
fh = open(“hello.text”, “r”)
print fh.readline()
fh = open(“hello.txt”, “r”)
print fh.readlines()
fh = open(“hello.txt”, “w”)
fh.close()
You can also use this to write multiple lines to a file at once:
fh = open(“hello.txt”,”w”)
lines_of_text = [“One line of text here”, “and another line here”, “and yet another
here”, “and so on and so forth”]
fh.writelines(lines_of_text)
fh.close()
To append a file:
fh = open(“hello.txt”, “a”)
fh.write(“We Meet Again World”)
fh.close
fh = open(“hello.txt”, “r”)
print fh.read()
fh.close()
With Statement
You can also work with file objects using the with statement. It is designed to provide
much cleaner syntax and exceptions handling when you are working with code. That
explains why it’s good practice to use the with statement where applicable.
One bonus of using this method is that any files opened will be closed automatically
after you are done. This leaves less to worry about during cleanup.
To use the with statement to open a file:
with open(“filename”) as file:
Now that you understand how to call this statement, let’s take a look at a few examples.
You can also call upon other methods while using this statement. For instance, you can
do something like loop over a file object:
with open(“testfile.txt”) as f:
for line in f:
print line,
You’ll also notice that in the above example we didn’t use the “file.close()” method
because the with statement will automatically call that for us upon execution. It really
makes things a lot easier, doesn’t it?
To better understand the with statement, let’s take a look at some real world examples
just like we did with the file handling functions.
with open(“hello.txt”) as f:
data = f.readlines()
This will take all of the text or content from the “hello.txt” file and store it into a string
called “data”.
As a final example, let’s explore a unique function that allows you to split the lines taken
from a text file. What this is designed to do, is split the string contained in variable data
whenever the interpreter encounters a space character.
But just because we are going to use it to split lines after a space character, doesn’t
mean that’s the only way. You can actually split your text using any character you wish -
such as a colon, for instance.
The code to do this (also using a with statement) is:
The reason the words are presented in this manner is because they are stored – and
returned – as an array. Be sure to remember this when working with the split function.