PYTHON MADE SIMPLE (2015)

Chapter 11: Reading and Writing Files in Python

In the last chapter, we learned how to be able to open and close a file.

A file that is open can allow reading and writing depending with the mode selected for execution in Python. Using the file objects allows one to access methods that will enable one to manipulate data in various ways. This makes life for people easier. In this chapter therefore, we would like to know how we can be able to read file using the read() and write() methods for reading and writing files.

Using write() Method

This attribute allows one to add anything in the form a string to an open file. Note that Python strings need to have binary data and may not just accept any form of text to be used in this case.

In addition, using the write() technique many not introduce a newline character ('\n') at the end of the string.

The syntax for the write() can be expressed as below

Here, is an example of how this can be applied in the real Python code:

Since, this file does not exist in python, it will create a new file called “goodmen.text” and then it will close after execution of the filename object.close ().

When the file is opened, it will contain the following text in it. Open it in Notepad.

How to use the read() attribute in Python

This method allows strings to be read from an open file. The python strings may contain binary data besides the use of the data in text.

The syntax for reading files is expressed as follows in Python:

In python, the file object is the assigned name in python at the time the file is being opened. For instance, goodmen files above were assigned an object value f2.

In this case, this allows the file opened to be read from the start of the file and when the count is absent, then, it will read the entire document to the end of the file. Hence, it is important to specify how much information may be needed when trying to get specific information in Python.

Note: You direct Python to do everything that you would like it to do.

For example:

Using the previous file in this chapter “goodmen.txt

We can read the above file in python and see what results it generates in Python.

The output will be expressed as follows:

Getting the positions of files

This is the method that can be used in finding the position of a text within a file. This uses the tell() attribute in python. This allows Python to do the next read or write from the position indicated from the beginning of the file created.

However, we can also be able to change the current file position of a file using the seek(offset[, from]) method. The argument offset; suggests the number of bytes to be moved while the other argument, from shows the specific position where the bytes will be moved from the current position.

When the value from is set as zero (0), This suggests that the file has to be read from the beginning of the file as the main reference point while a value of one (1) is used to refer t the current position. A value of 2 is applied to indicate the end of the file as the main reference point.

Using an example below:

Let us take a file foo.txt, which we created above.

The output will be as represented in the screen shot below:

How to Rename and Delete Files

Python also allows one to be able to process files in the python os. This includes processes such as being able to rename file or delete files without the need to manually delete the files. This can best be applied first by the use of the import statement and then you will be able to call any functions that can be performed.

Using the rename() syntax

The rename() attribute allows one to use two arguments. First, you will be required to use the current filename and then followed by the new filename.

A good example of the application is as shown below:

Following is the example to rename an existing file test1.txt:

Deleting files using the remove() Method

This is applied when one has to delete a file. This requires that you will have to provide a name of the file that has to be deleted in the argument.

The main syntax for the process is:

The following is an example on how to delete an existing file created as goodmen2.text.

Working with Directories in Python

All files are contained within various directories, and Python has no problem handling these too. The OS module has several methods that help you create, remove, and change directories.

The mkdir() Method

You can make a directory using the attribute mkdir() method inbuilt with the OS in Python. This will be able to create a new directory in the current directory. This is done by introducing an argument that will contain an argument which will have the name of the directory that needs to be created. The syntax to be used is:

os.mkdir("newdir")

The following example can be used for creating a new directory (new_programs) in the current directory.

Changing directory Method

To change the directory, use the attribute chdir() to change the details of the current directory. This is an argument that makes the new current directory.

It has the syntax as follows:

os.chdir("newdir")

As a good example for this syntax, let’s change to the current new directory "/home/working_programs".

How to get the current working directory

This is achieved by the use of the getcwd() attribute in python. It can be able to display the current directory that is working.  The syntax used is expressed as:

os.getcwd()

A perfect working code for getting the working directory is as shown in this screen shot

How to delete a directory

This is the technique which one can apply when they want to remove a directory. The attribute in function for this process is the rmdir()

This method enables one to delete completely the directory. This is initiated as an argument in Python. However, note that all the contents that had been previously saved in the directory will need to be removed first before it can be deleted. The syntax for the argument is set as:

os.rmdir('dirname')

To remove “tmp/new_programs” as a directory. The full name as it appears in the directory is provided. Hence, it will search for the name in the current directory.

Manipulation of files and directories

There are two special methods which allow one to be able to handle and manipulate different files and directories. These are applicable in both windows, Unix OS.

They include the following methods:

·     File Object techniques: The file object allows a function to change files.

·     OS Object techniques: enables the processing of both files and directories.

Summary

In this chapter, we have just learned that we can be able to delete a directory, create a new directory, change a directory, get a directory name and many other functions. This is an important process in Python. It makes life easier. You will be able to create a file in Python, create a new directory, save it there and even confirm if the file has been saved, and close the file as usual.

Practice Exercise

1.              A new file named “1000_keywords.csv” has to be opened, read as a binary file. Write a Python code that will execute this process.

2.              The file name also has to be changed to “Smart_words.csv” write a program that will execute the process and stored in the same directory. 

3.              John is working and is not sure in which directory he has been saving his work. Write him a two line program that will be able to identify the directory he has been saving his work.

4.              John has two long lists of students that he needs to merge them together. How can he be able to create a single list of names in Python? How can he also be able to save the list in his current directory named “students”? To avoid confusion, he will be required to delete the other original files in the current directory and save the same files in a different directory named “Old records”. Develop a single python that will be able to accomplish this process.

5.              Mike is a tutor for a school. The final exams were done and he has finished marking. However, he has to calculate the overall marks by adding the mean of the cat marks for cat 1 and cat 2 which account for 30% and add the marks to the final exams mark which is out of 70%. He has only a day to go before the deadline. How can he be able to do this automatically without much hustle in Python and accomplish the task in less than 10 minutes for 60 students?