image
image
image

Chapter 8: File Input and Output Inside Python

image

When it comes to working on a code inside of Python, there are times when you wish to store the data so that it is available for you to use later on when needed. You can choose to save it in a way that you can find all or part of it later on. Often you won’t need all the code right away but you will want to make it easier to find the information that you need or to pull it up later when the code is executing it. You will be able to save this information on what is known as a file on the disk, but you can also keep reusing the code over and over again inside the code, as long as you are taing the right steps. Here we are going to take some time to look at how you can handle some of the files inside of your code to make it work the way that you would like and to save it properly.

There are several things that you are ableto do when you work inside the file mode with Python. A good way to think about this is like when you work with Word and you are trying to save one of our documents. The only difference in this is that you aren’t saving any pages but rather you are saving some code inside of the program. Some of the different operatings that you can work with when it comes to working in files include:

Writing some new code onto a file that you already created

Seeking, or also moving the file over to a new location

Closing up the file

Creating a brand new file.

Each of these will help you to control what is inside the file, but you will need to handle them in different ways because they will tell the interpreter how to act. Here we will take a quick look at how each of them will work so that you are able to control the files in a way that you want.

How to create a new file

One of the first things that we are going to talk about with this is how you can create a brand new file to hold onto your code. If you would like to create a new file and be able to write on it, you first need to open it up inside of your IDE and then choose the mode that you wish to use when writing in it; there are a few options that you can choose from. The three options that you as the programmer are able to choose when you are writing in your code include mode(x), write (w), and append (a). If ther eare times when you want to make new changes to a file that you have open, you can use the (w) option because it is the easiest.

Any time that you would like to open up the file and write out a new string inside of your file, you will work with what are known as binary files, but you will need to use the write() method. This is going to work out well because it will return the right characters that you will be able to write into the file and itmakes it much eaiser to add in any changes, or write out new content, as it is needed, inside of the file.

The write() function is really easy to use and allows you to make as many changes to the file as you would like. You can add in some new information to the file or you can make some changes to one that you opened up. If you are interested in doing the writing in the code,  you can use this example to make things easier:

#file handling operations

#writing to a new file hello.txt

F=open(‘hello.txt’, ‘w’, encoding = ‘utf-8’)

f.write(“Hello Python Developers!”)

f.write(“Welcome to Python World”)

f.flush()

f.close()

Take the time to add this into the compiler and when it is done, you are basically making sure that all the information that you are creating will go inside the current directory so you may want to make sure that you are in a directory that will work for storage or at least one that you are ableto remember. So whatever directory you are in right now is the one you will ahve to go back to when you are searching for the file, in this case the hello.txt file. When you find this file in the directory and try to get it to open, you will get the message “Hello Python Developers! Welcome to Python World.”

Now that the progarm is written out, there may be some times when you would like to do an overwrite of the program so that it will get something else to show up on the file that is already created. It is possible to do this with the write coding inside of Python, we just need to make some changes to the syntax and add in a few more things. An example of how you can do this includes:

#file handling operations

#writing to a new file hello.txt

f=open(‘hello.txt’, ‘w’, encoding = ‘utf-8’)

f.write(“Hello Python Developers!”)

f.write(“Welcome to Python World”)

mylist=[“Apple”, “Orange”, “Banana”]

#writelines() is used to write multiple lines in to the file

f.write(mylist)

f.flush()

f.close()

This is a great example of how you would be able to make some changes to a file that you already wrote out because you simple need to add in an additional line. Of course in this example you probably wouldn’t use that third line since it is just some simple words, but you are able to add in anything that you want to the program and you would just use the same syntax that is above.

How to work with binary files

Another thing that you may need to deal with when you are working on these files is when you would like to write out your data so that it is considered a binary file. This is a simple process to do within Python because you will just need to take the data and write it out as a sound or image file rather than a text file. You can change any text that you are writing inside of Python into a binary file, no matter if it was a sound, picture, or text file in the beginning. The most important thing for you to understand in this is that you must supply the data inside of the object so that it can later be exposed as a bite. The syntax that you can use in order to write the text as a binary file includes:

# write binary data to a file

# writing the file hello.dat write binary mode

f=open(‘hello.dat’, ‘wb’)

# writing as byte strings

f.write(b”I am writing data in binary file!/n”)

f.write(b”Let’s write another list/n”)

f.close()

Before we move on, take some time to open up the compiler and write this all out. Make sure that you have the encode and decode functions in place so that it is easier to write out and even rad the text out in your file for binary mode. If you want to allow this to happen inside of your code, make sure that you write out the following code example:

#write binary data to a file

#writing the file hello.dat write binary mode

f=open(‘hello.dat’, ‘wb’)

text=“Hello World”

f.write(text.encode(‘utf-8’))

f.close()

Opening up a file

In the two examples that were above, we spent some time talking about how to write the words that go on the file and how to change the text so that it is a binary function. Now there are going to be times when  you would like to open up a file so that you are able to use it again. The code that you write is stored onside the computer so you just need to find these in order to open them up again. Here is an example of how you would do this!

#read binary data to a file

#writing the file hello.dat write append binary mode

with open(“hello.dat”, ‘rb’) as f:

data=f.read()

text=data.decode(‘utf-8’(

print(text)

the output that you would get form putting this into the system would be like the following:

Hello world!

This is a demo using with

This file contains three lines

Hello world

This is a demo using with

This file contains three lines.

Seeking one of your files

In addition to doing some of the tasks that we talked about above, there are also time when you may want to make changes to some of your files or find a way to move around. For example, if things aren’t matching up the way that you would like, you misspelled the words of the name, or you placed it into the wrong dirctory, you may want to use the seek option to make the changes.

You will be able to go through and change up the position where the file is so that it goes to the right spot, or even so that it becomes a lot easier for it to find. You just need to tell your code where you would like to find the code and then make the changes that are needed.

Working with files in the Python language will help you out a lot when you are trying to get things in order inside your code, when you want to make changes to what you wrote, and so much more. Try out a few of the codes that are inside this guidebook and see just how easy it can be to create a new file, make changes, and get the files to work the way that you would like.