Working with Files in Python

In the first blog post I created we talked about **kwargs and *args in python. You could check it out here. If you haven't seen that article, you needn't fret. We would be talking about files today and it can be understood without prior knowledge of non-keyword and keyword arguments.

When working with files in Python, the rules are pretty easy. Outside programming in word documents for instance, they are only handful of operations you carry out on files. You open them, you create them, you write in them, you read their content and you delete their content. Those are the basic operations. If your files can teleport you well...that's something I could use.

Opening Files

newFile = open('someFileThatExists.txt')
# Perhaps do something with the file
newfile.close()

The above simply opens a file that exists. If the file doesn't exist, you'd be sure to get some angry messages thrown back at you. In addition, we close the file as seen above. This is a good practice. What if you would like to create a new file, one that didn't exist prior? You'd have to use something known as a mode.

Modes

Python file operations are carried out with the help of some very important concepts known as modes. These modes allow us to do the basic operations with files as stated above. For instance to create a new file one can use the 'x' mode, to read a file one can use the 'r' (read) mode, to write to a file and in so doing remove whatever existed prior in the file we use the 'w' (write) mode and to append data to an existing file we use the 'a' (append) mode. The code snippet below states these different modes that concern opening and creating files.

# To create a new file without overwriting any existing file with the same name.
newFile = open("someNewFile.txt", 'x')

# To create a new file that will overwrite any existing file with the same name.
newFile = open("someNewFile.txt", 'w')

# Close the file
newFile.close()

It is important that you note the difference between these two modes so that you do not accidentally overwrite some important information in a file that could land you in a lot of trouble.

Reading Files

If you would like to display the contents of a file after opening it, or use it in some way (like print it) you can add 'r' (the read mode). You would have to add the read() method to be able to print the content of the file. You should note however, that if you neglect 'r' and just open the file, you would still be able to print its data.

# To read a file
existingFile = open("someFile.txt", 'r')

# You can choose to print the content of the file by using the read() method...
print(existingFile.read())

# Now you can close the file
existingFile.close()

What if we would like to consider individual lines in the file instead of all text at once? We would need to use readlines for that.

#Open the file
existingFile = open("someFile.txt", 'r')

#Content of the file would be printed in the form of a list, with
#each line representing an item (You would learn about lists soon
#if you don't know what they are)
print(existingFile.readlines())

# Now you can close the file
existingFile.close()

Writing To Files

There are two major ways to write to files in python and they produce very different results. We can either write to 'w' a file and in so doing delete everything in the file, replacing it with our data or append to 'a' a file, simply adding data to the existing data on the file. You can test this out, by adding data to a file and trying out the code below. We use the write() method to add content to a file irrespective of the write mode.

# Write data to a file, thereby removing everything in the file
someFile = open('someExistingFile.txt', 'w')

# Add data to the file using write()
someFile.write("According to Albert Camus, the universe is inherently meaningless\n")

# Close the file
someFile.close()

If any text existed in that file, before you added your philosophy text, that text would vanish and be replaced by the statement you have added. If you don't want this to happen, you can use the snippet below instead.

# Append data to a file
someFile = open('someExistingFile.txt', 'a')

# Append data to the existing data in the file using write()
someFile.write("I did feed my cat today though, and that was meaninful to me so I guess I create meaning.\n")

# Close the file
someFile.close()

In this case, data would be added to the file. Now you not only acknowledge Absurdism according to Albert Camus but you add that you create your own meaning.

Using 'with'

You must notice from the above that each time we opened a file, we had to close it. What of situations where you forget to do so? Not closing a python file makes you run the risk of losing data. If a computer crashes, it would be possible to corrupt files that are not closed. This is because this new data you've written is actually written to a buffer which stores the data only temporarily. There is a risk of losing data if the file is not properly closed. Only data on closed files can then be written to the disk.

If remembering to close a file all the time is a hassle for you, you can use the 'with' statement to open a file and not worry about it.

with open('someExistingFile.txt', 'a') as someFile:
    someFile.write("I am adding these lines to my philosophy wisdom")

There is no need explicitly closing the file with the above code. This is done automatically.

Now you know how to work with files using python code. You can create them, read their data and write to them. You also understand why it's important to close files. How about trying to build a program that combines the subject of kwargs and args with file operations in python.

0
Subscribe to my newsletter

Read articles from Amanda Ene Adoyi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Amanda Ene Adoyi
Amanda Ene Adoyi

I am a Software Developer from Nigeria. I love learning about new technologies and talking about coding. I talk about coding so much that I genuinely think I could explode if I don't . I have been freelance writing for years and now I do the two things I love the most: writing and talking about tech.