Simple Arithmetic, Input and Output in Python

File Processing

Now that we can receive input, process that input and output it to the terminal, we should find a way of storing data in a file and use data from exiting files.

open()

my_file = open("path_to_my_file")

will open the file located in path_to_my_file and return a file handle stored in the my_file variable.

read()

my_file = open("path_to_my_file")
print(my_file.read())

will read the contents of the entire file and display it on the screen.

read(number_of_characters)

my_file = open("path_to_my_file")
print(my_file.read(10))

will read as many as number_of_characters from file and display them on the screen.

readline()

my_file = open("path_to_my_file")
print(my_file.readline())

will read a single line from the file each time it is called from the my_file file handle. Each call will retrieve the next line after the previously read line if any. Each time the file is opened the position pointer of the file is reset to the beginning.

my_file = open("path_to_my_file")
print(my_file.readline())
print(my_file.readline())
print(my_file.readline())

close()

my_file = open("path_to_my_file")
print(my_file.read())
my_file.close()

It is important to close() the file if it is not required any longer. This will free system resources which you will need later on.

Mode Arguments of open()

The modes of opening a file are as follows:

The modes "a" and "w" will create the file if it does not exist in the storage, however, the mode "x" will return an error if the file already exists. This is a means of warning to the user not to overwrite or append accidentally to a file which is not intended to be modified. Similarly the mode "r" will return an error if the file does not exist. The modes are mutually exclusive, i.e. they cannot be used together.


There are two more mutually exclusive modes of opening a file, that can be used with the above modes:

The open() function uses readonly text mode if no mode argument is specified, i.e.

my_file = open("path_to_my_file") is equivalent to

my_file = open("path_to_my_file","rt").

write()

In order to write to a file we need to open it with either of the "a" or "w" modes.

In order to everwrite the contents:

my_file = open("path_to_my_file","w")
my_file.write("This text will overwrite any content in the file.")
my_file.close()

To append to the end of the file:

my_file = open("path_to_my_file","a")
my_file.write("This will append this text content to the end of the file.")
my_file.close()

You can experiment with reading from files using the following example:

print("Reading the entire content:")

demo_file = open("resources/FileReadingDemo.txt")

print(demo_file.read())

demo_file.close()

print("--------------------")
print("Reading 20 characters from the file")
demo_file = open("resources/FileReadingDemo.txt")
print(demo_file.read(20))

print("Reading 20 more characters from the file")
print(demo_file.read(20))
demo_file.close()

print("--------------------")
print("Reading two lines from the file, beware of the extra newlines")
demo_file = open("resources/FileReadingDemo.txt")
print(demo_file.readline())
print(demo_file.readline())
demo_file.close()

my_demo_file = open("resources/FileReadingDemo.txt","at")
my_demo_file.write("\nThis is additional content written using the append mode.")
my_demo_file.close()

print("--------------------")

If an error occurs due to missing file or if the file cannot be created in the file system, then the program may crash simply not knowing how to proceed. Try the example with a non-existing filename:

file_name = input('Enter the file name: ')
file_handle = open(file_name)

print("File opened successfully")
file_handle.close()

In order to prevent such cases the exception handling procedure, i.e. try-except structure, should be used anywhere that has a potential of generating a system error, namely a runtime exception :

file_name = input('Enter the file name: ')

try:
    file_handle = open(file_name)
    print("File opened successfully")
    file_handle.close()
except:
    print('File cannot be opened:', file_name)