File I/O - Python Made Easy (2013)

Python Made Easy (2013)

Chapter 8: File I/O

“Our society expects that everyone should learn to write, even though very few become professional writers. Similarly, I think that everyone should learn how to program, even though very few will become professional programmers.”- Mitchel Resnick

This chapter will teach you about

· Input/output files

· Methods

· Directories

· Types of methods

· Cursors

Now that you know how to load external code into your programs, we will look into file input and output with normal text files. This is ideal for when you would like to store information in a text file, call for information from that text file, or use it in a variety of ways. File I/O commands are important, and used in any large scale Python program.

What is File I/O?

File I/O refers to using (inputing and outputing) data using normal text files. There are a number of commands and functions built directly into Python that allow you to create, open, append, and call to text files and the information stored on them. You can pass parameters, and use them as data dumps that can be called to at a later date.

You can also put information into Python and it will then, produce the same information/data on to your screen. All you need to do is to use the print statement for this. Print will convert the expression into a string and this will enable Python to display the message on your screen. For example, if you put inprint “I am using Python,” , “I love using this programming language!”; Python will produce the following output:

I am using Python, I love using Python!

Let's take a look at some of the basics of File I/O now, and look at how they might be used in the programs that you create.

Opening Files

In order to open files, you will be using the open() function. It is fairly self explanatory. You pass parameters to the open() function, telling it how you would like it to open the file. A few of the different parameters that you might pass to the files include;

· r – for read-only files.

· w - for write-only files.

· a – for appending files.

· r+ - for both reading and writing files.

These same parameters are present throughout your operating system and in other programming languages as well. Opening a normal text file is relatively simple and straightforward. Here is an example of opening a file using Python;

openfile = open('pathtofile', 'r')

openfile.read()

This instructs the program to open a file at a given path and then read the contents of that file. The text in .txt files is completely unformated. You can also print the information that the program reads with the following code;

print openfile.read()

This allows you to display any of the data that is stored within the text file. Try typing this into your IDE now.

Did it work? Probably not. We are introducing a new concept that has not yet been covered in this book. You failed to print the read data because the cursor had changed positions.“Cursor? What Cursor?” you are probably asking right now.

Cursors

A cursor is an unseen market of where the program will read functions from (along with other I/O functions), letting it know where to start from. In order to set the cursor where you need it to be, you must use the seek() function. The seek() function is used in the following form;

seek(offset, whence)

· Whence - Whence is an optional inclusion within the seek() function. When the whence is 0, the program will read and count all of the bytes and letters contained within the text file from the very beginning. When it is set to 1, the bytes will be counted from the current position of the cursor. If it is set to 2, then the bytes are counted from the end of the file only. When there is nothing in its stead, 0 is assumed by the program.

· Offset– The offset describes how far from whence the cursor movies. So for example, an offset of openfile.seek(45,0) would move the cursor 45 bytes from the beginning of the file. An offset of openfile.seek(10,1) would move the cursor 10 byes from the current position of the cursor. Negatives can also be used, which denote the position from the end of the file. For instance, openfile.seek(-77,0) would move the cursor 77 bytes behind the end of the file.

This may seem overly complicated of reading.txt files, and it definitely is for the basic commands. But, this function provides deeper functionality, allowing you to determine where the program begins reading the file from. This provides versatility when working with.txt files.

Other I/O Functions

There are a large number of different I/O functions that you can call on and use when dealing with .txt files. These functions include;

raw_input

What this function does is that it will read a standard input line and then, return the same line in the form of a string.

string= raw_input (“Enter your input: ”)
print “Received input is : ”, string

Now, any string you enter will be read and displayed on to your screen.

Enter your input: I like Python
Received input is: I like Python

This message will also show on your screen.

Input

The input and raw_input functions are very similar to one another. The only exception is that input assumes that anything entered into the program is valid and the result evaluated by the function is then, returned to you.

str= input (“Enter your input: “);
print “Received input is :” str

Now, let’s put in some values to see what happens:

Enter your input: [a-2 for a in range (2, 12, 10)]
Received input is: 0, 10, 8

tell()

Returns where the cursor is currently located within the file. There are no additional parameters with this function. It is useful for determining how your code is effecting the placement of the cursor, and provides added control. You can access it by typing fileobjectname.tell() - with fileobjectname being the name of the file that you are opening. The position of your cursor may change as your code runs, and tell() is very useful for examining how your code effects the placement of that cursor.

seek (offset[, from]) method

A file’s current position is changed using this method and offset is an argument that will indicate the quantity of bytes that should be moved. The ‘from’ argument will tell you where the file needs to be moved from.

When from is set to 0 this means that the bytes need to be moved from the beginning of the file. If it is set to 1 that means the bytes have to be moved from the current position of the file and if it is set to 2 the end of the file is considered to be the reference position of the file.

readline()

This function reads from where the cursor is currently located until the end of the line. The end of the line is not the edge of the screen, it is where“enter” is hit, creating a new line in a .txt file. Remember that an individual line can go on an unlimited amount in a text file. There are no parameters that need to be passed when using readline().

For instance, if you had an example text file that looked like this;

Line 1

Line 3

Line 4

Line 6

The returned list would look like this;

Index 0 = Line 1

Index 1 =“

Index 2 = Line 3

Index 3 = Line 4

Index 4 =“

Index 5 = Line 6

Each line in a .txt file constitutes a different index within the code. This makes the placement of your data predictable.

When you want to create a new line, you use the following command:“\n” at the end of any string.

renaming & deleting files

When renaming your file you need to use 2 arguments- the current filename and the filename that you intend to use in order to rename the existing file. The syntax for this is as follows:

os.rename(current_file_name, new_file_name)

write()

The write() command, as you might guess, is used to write data to the file. It writes from the position of the cursor, and will overwrite any text that comes after it. If you would like to add information to the end of the already stored data, make sure that your cursor is set to the end of the file. You can also use writelines() for writing multiple lines to a single .txt document.

close()

Close is typically used to close the file that it can no longer be used for reading or writing the data. The close() command is one that can help you to ensure that data is not inadvertently edited past the pont that you would like it to be.

read() method


This method, as is obvious by the name of the method, will read a string in a file. Here s the syntax for the method:

fileObject.read([count]);

The method will read the file from the very beginning. If count cannot be detected by the method (because it is missing), it will read as much data as it can.

Directories

The files are contained in the directories and Python can easily access these. Python’s OS module can be used to create, modify, change and move the directories, too.

The mkdir() Method


This method is used to create new directories within the existing directory. To do this you need to provide the method with an argument that contains the name of the directory that you intend on creating. The syntax for this is as follows:

os.mkdir(“yournewdir”)

So, let’s create a directory entitled ‘mynewdir’ within a directory that already exists:

import os

os.mkdir(“mynewdir”)

The chdir() Method

If you feel the need to change or modify the current directory, you’ll have to use this method. This method will take the argument, which is also the directory’s name, so you can introduce changes to and existing directory.

The syntax for this is as follows:

os.chdir(“yournewdir”)

Now, if you you want to go into the “/mycomputer/newdir” directory, this is how you will do so:

import os

os.chdir(“/mycomputer/newdir”)

The getcwd() Method

This method will only display the existing and working directory. The syntax for this is as follows:


os.getcwd()


Here’s an example of how this method can be used:

import os
os.getcwd()

The rmdir() Method

This method is used to delete a directory that has been passed in the form of an argument in a method.

PROJECT: File I/O

Using our previous examples, create a document, newfile.txt that says“Hello world” on one line, and“Hello FileI/O” on another line, then read it and print it.

Answer:

file = open("newfile.txt", "w")

file.write("hello world in the new file\n")

file.write("and another line\n")

file.close()

file2 = open('newfile.txt', 'r')

print file2.read()

Summary

ü This chapter covers the following:

· Input/output files

· How to open files

· Cursors

· How to use cursors

· Directories

· Different types of methods

· How to use different types of methods