In the deliveries In previous lessons of this Python programming course using Linux, we saw that data could be entered from lists, tuples, and dictionaries, or by asking the user to enter it manually. Now we will see how to work by reading or saving files.
With the import of the necessary modules, Python can read, create, and write to various file formats, including those of the most popular office suites and PDF; however In this post we will stick with text files for the time being.
Python programming course using Linux. Part Fourteen
Plain text files are the most basic way to store datas. These are letters, numbers, symbols, and spaces stored on lines without any formatting. This is the type of file created with programs like Gedit, Kate, or Windows Notepad.
Being compatible with most programs and programming languages, Plain text format is used to store simple information such as settings, activity logs, lists, or program execution results.
From its installation, Python includes the basic commands for working with text files, including opening, reading, writing, and closing them.
The open() function
This function requires two parameters: the file name and one of the following:
- r: Read an existing file.
- w: Checks if the file exists, creates it if it does not exist, and overwrites its contents if it does.
- r+: It combines reading and writing to the file.
- a: Write below the file content.
For example, this instruction:
archivo = open("archivo.txt", "r")
- Open the file and read its contents.
- The variable stores the object that the open function creates when opening the file.
With this program we open the file, read and print its contents, and close the file.
archivo = open("archivo.txt", "r")
contenido = archivo.read()
print(contenido)
archivo.close()
This program
- Open the file in read mode and assign the object to the file variable.
- The read method assigned to the file object variable reads the content using the read method and assigns it to the content variable.
- Prints the content stored in the content variable.
- Close the file.
Now let's look at another way to read the contents of a file;
In this case we use another method called readlines.
- The program opens the file in read mode, creates the object, and assigns it to the file variable.
- The function file.readlines creates a list with all the lines of the text file and assigns it to the variable lines.
- The loop prints line by line with a detail. Since plain text editors include a special character to indicate line breaks, the strip method removes that character from the printout.
- The file is closed.
We can write a file with a program like this
archivo = open("archivo.txt", "w")
archivo.write("Hola, estamos escribiendo un archivo.\n")
archivo.write("usando un programa en Python.")
archivo.close()
- The program opens a file or creates it if it does not exist, creates an object and assigns it to the file variable.
- Write the first line by adding the write method to the file variable. .\n indicates that there should be a line break.
- Write the second line.
- Close the file.
Another method of writing to a file:
archivo = open("archivo.txt", "a")
archivo.write("Voy a agregar una línea más.")
archivo.close()
This program opens the file using the parameter 'a' to indicate that the text should be included after the current text.
Let's try a combined example:
This program does the following:
- Create the file distributions.txt in write mode, create an object for Python to work with, and assign it to the variable file.
- Write the names of three distributions in the file, followed by a line break, so that they are ordered in columns.
- Close the file.
- Open the file in read mode, create the object for Python to work with, and assign it to the file variable.
- Prints on screen the message that it will display the contents of the file.
- Start the loop to read the file's contents line by line.
- Prints line by line omitting the line break indicator character.
- Close the file.
error handling
Often, due to coding or user errors, situations can arise that prevent the program from continuing to function. Python usually halts execution and displays an error message. However, we can take steps to prevent this. This is called exception handling.
Python has a mechanism for handling problems (or exceptional situations) known as the try-except blockThe `try` block contains the code that Python assigns to the error, and the `except` block contains the code that should be used to respond to that error. An error would be, for example, trying to open a file that doesn't exist or writing to a file for which the program doesn't have sufficient permissions.
- We start the block of code that Python should execute with the try instruction.
- We open the file (assuming it exists) in read mode.
- We assign the file content to the variable content.
- We print the title "File Contents"
- We print the content.
- We closed the file.
- If the program cannot find the file, it displays two messages indicating that the file does not exist and that we should check the name.
Most common types of errors:
- ValueError: An attempt is made to use an invalid value in an operation or function.
- TypeError: An attempt is being made to use an invalid data type in an operation or function.
- IndexError: You want to access a non-existent index in a list or tuple.
- KeyErrorAn attempt is being made to access a key that does not exist in a dictionary.
- FileNotFoundErrorAn attempt is being made to access a non-existent file.
- ZeroDivisionError: An attempt is made to divide a number by zero.
- AttributeError: An attempt is made to access a non-existent attribute in an object.
- ImportErrorThis occurs when you try to import a module that does not exist or when errors occur during an import.
In future articles we will continue with this course