<div class="text-justify">
<center><h1>Putting File Handling into practice</h1></center>
<center>

<br>[Shoutout to Infovistar](https://infovistar.com/python/file-handling)</center>

<center><h3>In this article you'll find:</h3></center>
* <b>Introduction</b>
* <b>Example 1</b>
* <b>Example 2</b>
* <b>Example 3</b>
* <b>Example 4</b>

In the previous two chapters of Coding Basics, we looked at how to handle files in different ways. From reading, writing and renaming files to creating and deleting them, we understood the main functions that allow us to interact with directories in our operating system.
However, so far we have only seen the theoretical component, where we are briefly shown how they work. However, this is no guarantee that we will know how to apply it in a program when we need it.
This is why, in order to ensure that we have absorbed the knowledge correctly, we will see some examples of File Handling, both through open() and with the os module. Having said that:
<center>Let's get started!</center>

<center><h2>Example 1</h2></center>
<center>

<br>[Shoutout to Software Testing Help](https://www.softwaretestinghelp.com/python/python-file-reading-writing/)</center>
For this first example, we start with something simple. We have a text file in our current directory, which presents the following text:
```
The*best*we*can*do*is*go*to*the*mall,*the*greatest*one*I*have*ever*seen.
```
Now, we are asked to print this text on one condition: That we remove the asterisks and put spaces in their place.
How do we do this?
The first thing we must remember is the existence of .read(), a method specific to file-type objects that allows us to read the contents of the file.
```
file = open('TextFile.txt', 'r')
reading = file.read()
```
In this case, because the file is in text form, it will return a string, which we can use to our advantage.
We know that if we apply a for loop to a string, it will loop through each of the characters in the string, as if they were the elements of a list. Now, we just have to make it so that when it detects a '*' character, it changes this to a space.
Finally, for this to be carried out, we apply an if conditional, which will ask us if the character is '*'. If it is, it will print a blank space, and if it is not, it will print the character in question. So:
```
file = open('TextFile.txt', 'r')
reading = file.read()
for letter in reading:
if letter == "*":
print(" ", end='')
else:
print(letter, end='')
file.close()
```
> Note: Remember that it is good practice to close an open with the close method, thus allowing new files to be opened and read in subsequent operations.
And if we convert it into a function, executing it, we will have:
```
def read_words():
file = open('TextFile.txt', 'r')
reading = file.read()
for letter in reading:
if letter == "*":
print(" ", end='')
else:
print(letter, end='')
file.close()
read_words()
>>> The best we can do is go to the mall, the greatest one I have ever seen.
```
> Note: If you are wondering what that end="" is that we use in the print, this is a parameter that allows us to determine which character we place when we finish writing the string.
> By default, this character would be \n, which would cause each letter to be written on a new line.

<center><h2>Example 2</h2></center>
<center>

<br>[Shoutout to DataCamp](https://www.datacamp.com/tutorial/python-string-split)</center>
We continue with the use of open and read, but this time, we will not use it to replace a character, but to determine the number of times a word appears in the file.
In this case, the word will be The, in both upper and lower case. If you already know how to run this program, do it on your own and comment on the solution.
In case you want to know how to do it, keep reading:
So that we can count the number of times a word appears, we will use not only open() and read(), but we will also use another of the file object methods, which is split()
If we refresh our memory, split() allows us to separate the characters from the string resulting from read(), converting them into a list, where the space character is what distinguishes the elements.
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
```
If we printed the value of wordlist, we would have the following:
```
>>> ['The', 'best', 'we', 'can', 'do', 'is', 'go', 'to', 'the', 'mall,', 'the', ' greatest', 'one', 'I', 'have', 'ever', 'seen.']
```
Now, as we already know, we would have to use a for loop to go through each element in the list. In this case, since we are looking for the word the, we again use a conditional to identify "the" or "The"
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
for word in wordlist:
if word == 'The' or word == 'the':
```
However, we also need something that allows us to count the number of times 'the' appears. For this, we just define a counter variable that will initially be 0, and every time we find the match it increases by one.
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
count = 0
for word in wordlist:
if word == 'The' or word == 'the':
count += 1
```
Finally, if we print and remember to close the file with close():
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
count = 0
for word in wordlist:
if word == 'The' or word == 'the':
count += 1
print(f'The amount of times the word \'the\' appears is: {count}')
file.close()
count_words()
>>> The amount of times the word 'the' appears is: 3
```

<center><h2>Example 3</h2></center>
<center>

<br>[Shoutout to codingem.com](https://www.codingem.com/python-how-to-check-file-size/)</center>
Now, we start using the os module. Here, we will go to a folder that we created. In my case, it is called testfiles.
Inside this folder there are 3 text files with different sizes. Our task will be to verify that the files are not larger than 2 kb.
<center></center>
Now, as we can see, file1 and file2 comply with not being larger than 2kb. However, file3 is 8kb which will mean it will not pass the test.
In order to carry out the code that performs the verification, we use a function from the os module called listdir, which, as its name implies, creates a list from the files within a directory.
The only parameter that listdir asks us for will be the directory address. So:
```
import you
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
```
If we print the resulting value:
```
['File1.txt', 'File2.txt', 'File3.txt']
```
Now, to determine the size of each file, we apply a for loop to loop through each element of the list and use one of the functions we saw in the previous chapter:
* os.path.getsize()
This allows us to determine the size of bytes in a file, taking the file path as a parameter.
```
import you
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
for file in filelist:
path = os.path.join(dir_path, file)
fileSize = os.path.getsize(path)
```
> Note: We use os.path.join to join the directory path with the file name into a single address quickly.
Finally, we use another conditional to check if the file is longer than 2000 bytes, obtaining:
```
##Example 3
import you
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
for file in filelist:
path = os.path.join(dir_path, file)
fileSize = os.path.getsize(path)
if fileSize > 2000:
print(f'{file} has too much info. It will not get transferred')
else:
print(f'{file} verified. It can pass')
>>>
File1.txt verified. It can pass
File2.txt verified. It can pass
File3.txt has too much info. It will not get transferred
```

<center><h2>Example 4</h2></center>
<center>

<br>[Shoutout to Pi My Life Up](https://pimylifeup.com/python-file-exists/)</center>
For the last example, we will use two concepts that we have seen previously:
* File management.
* The use of try except.
Here, we encounter indecision about the path of a file. We don't remember if it is in the main directory of our examplemodules folder or if it is in the nestedfiles directory, within the same folder. For this, we will then take both routes.
Firstly, we will look to see if the texttowrite.txt file is located within examplemodules. In case it's not here, we'll look in nestedfiles.
To carry out this, we will use the try for the first case, where we search in examplemodules and use assert, an instruction that allows us to create a condition that, if met, allows us to execute the program normally. If the assert is not fulfilled, it will give us an AssertionError.
It is here, where we use the AssertionError for our except code, where we will change the path and check again to see if it exists.
In order to know if a file exists within a directory, we use the os.path.exists function, which asks us for the file path along with its name as a parameter.
Putting all this into practice:
```
import you
try:
file = 'texttowrite.txt'
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/'
path = os.path.join(dir_path, file)
result = os.path.exists(path)
assert result == True
print(f'The file {file} is located in {dir_path}')
except:
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/nestedfiles/'
path = os.path.join(dir_path, file)
result = os.path.exists(path)
if result == True:
print(f'The file {file} is located in {dir_path}')
else:
raise('The Value is in neither directory')
```
We can see that at the end, in order to check if it is really in any file, we use a conditional. If it is not found in either of the two directories, it will notify us.
So, if we run the program:
```
The file texttowrite.txt is located in C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/nestedfiles/
```
Which is true.
<center></center>

As you can see, becoming familiar with files and file management is a simple task that will be of great help when working with different types of files and manipulating the information within them in later modules.
After this series of 3 posts, you will already master file handling, knowing it like the back of your hand. This is why in the next post, we will see modules for managing different extensions.
We've come too far! Pat yourself on the back and consider yourself an intermediate student from now on.

<center>Thank you for your support and good luck!</center>



<center><h1>Poniendo el File Handling en práctica</h1></center>
<center>

<br>[Shoutout to Infovistar](https://infovistar.com/python/file-handling)</center>

<center><h3>In this article you'll find:</h3></center>
* <b>Introducción</b>
* <b>Ejemplo 1</b>
* <b>Ejemplo 2</b>
* <b>Ejemplo 3</b>
* <b>Ejemplo 4</b>

En los dos capítulos anteriores de Coding Basics, observamos como manejar archivos en distintas formas. Desde leer, escribir y renombrar archivos hasta crearlos y eliminarlas, entendimos las funciones principales que permiten interactuar con directorios en nuestro sistema operativo.
Sin embargo, hasta ahora solo hemos visto el componente teórico, donde se nos muestra de manera breve como funcionan. Sin embargo, esto no es garantía de que sepamos como aplicarlo en un programa cuando los necesitemos.
Es por esto, que en orden de asegurar que hemos absorbido el conocimiento correctamente, veremos algunos ejemplos del File Handling, tanto por medio de open(), como con el módulo os. Dicho esto:
<center>¡Empecemos!</center>

<center><h2>Ejemplo 1</h2></center>
<center>

<br>[Shoutout to Software Testing Help](https://www.softwaretestinghelp.com/python/python-file-reading-writing/)</center>
Para este primer ejemplo, comenzamos con algo sencillo. Tenemos un archivo de texto en nuestra directorio actual, el cual presenta el siguiente texto:
```
The*best*we*can*do*is*go*to*the*mall,*the*greatest*one*I*have*ever*seen.
```
Ahora, nos piden que imprimamos este texto con una condición: Que eliminemos los asteriscos y coloquemos espacios en su lugar.
¿Cómo hacemos esto?
Lo primero que debemos recordar es la existencia de .read(), un método propio de los objetos tipo file que nos permite leer el contenido del archivo.
```
file = open('TextFile.txt', 'r')
reading = file.read()
```
En este caso, debido a que el archivo está en forma de texto, nos devolverá una string, lo cual podemos usar a nuestro favor.
Sabemos que si aplicamos un ciclo for a una string, este recorrerá cada uno de los caracteres de la string, como si fuera los elementos de una lista. Ahora, solo tenemos que hacer que cuando detecte un caracter '*', cambie este por un espacio.
Finalmente, para que esto se lleve a cabo, aplicamos un condicional if, el cual nos preguntará si el caracter es '*'. En caso de que lo sea, imprimirá un espacio en blanco, y en caso de que no lo sea, imprimirá el caracter en cuestión. Así:
```
file = open('TextFile.txt', 'r')
reading = file.read()
for letter in reading:
if letter == "*":
print(" ", end='')
else:
print(letter, end='')
file.close()
```
> Nota: Recordar que es buena práctica cerrar un open con el método close, así permitiendo abrir y leer nuevos archivos en siguientes operaciones.
Y si lo convertimos en una función, ejecutándolo, tendremos:
```
def read_words():
file = open('TextFile.txt', 'r')
reading = file.read()
for letter in reading:
if letter == "*":
print(" ", end='')
else:
print(letter, end='')
file.close()
read_words()
>>> The best we can do is go to the mall, the greatest one I have ever seen.
```
> Nota: Si te preguntas que es ese end="" que usamos en el print, este es un parámetro que nos permite determinar que caracter colocamos al terminar de escribir la string.
> Por defecto, este caracter sería \n, lo que haría que cada letra se escribiera en una nueva línea.

<center><h2>Ejemplo 2</h2></center>
<center>

<br>[Shoutout to DataCamp](https://www.datacamp.com/tutorial/python-string-split)</center>
Seguimos con el uso de open y read, pero esta vez, no la usaremos para eliminar un caracter, sino para determinar la cantidad de veces que una palabra aparece en el archivo.
En este caso, la palabra será The, tanto en mayúscula como en minúscula. Si ya sabes como realizar este programa, hazlo por tu cuenta y comenta la solución.
En caso de que quieras saber como se hace, sigue leyendo:
Para que podamos contar la cantidad de veces que una palabra aparece, nos valdremos no solo de open() y read(), sino que también utilizaremos otro de los métodos de los objetos file, el cual es split()
Si refrescamos nuestra memoria, split() nos permite separar los caracteres de la string resultante del read(), convirtiéndolos en una lista, donde el caracter de espacio es lo que distingue a los elementos.
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
```
Si imprieramos el valor de wordlist, tendríamos lo siguiente:
```
>>> ['The', 'best', 'we', 'can', 'do', 'is', 'go', 'to', 'the', 'mall,', 'the', 'greatest', 'one', 'I', 'have', 'ever', 'seen.']
```
Ahora, como ya sabemos, nos restaría usar un ciclo for para ir por cada elemento de la lista. En este caso, como buscamos la palabra the, usamos de nuevo un condicional para identificar a "the" o "The"
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
for word in wordlist:
if word == 'The' or word == 'the':
```
Sin embargo, también necesitamos algo que nos permita contar la cantidad de veces que 'the' aparecen. Para esto, solo definimos una variable de contador que inicialmente será 0, y cada vez que encontremos la coincidencia aumente en uno.
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
count = 0
for word in wordlist:
if word == 'The' or word == 'the':
count += 1
```
Finalmente, si imprimimos y recordamos cerrar el archivo con close():
```
def count_words():
with open('Textfile.txt', 'r') as file:
reading = file.read()
wordlist = reading.split()
count = 0
for word in wordlist:
if word == 'The' or word == 'the':
count += 1
print(f'The amount of times the word \'the\' appears is: {count}')
file.close()
count_words()
>>> The amount of times the word 'the' appears is: 3
```

<center><h2>Ejemplo 3</h2></center>
<center>

<br>[Shoutout to codingem.com](https://www.codingem.com/python-how-to-check-file-size/)</center>
Ahora, comenzamos a usar el módulo os. Aquí, nos dirigiremos a una carpeta que creemos. En mi caso, se llama testfiles.
Dentro de esta carpeta se encuentran 3 archivos de texto con tamaños distintos. Nuestra tarea será verificar que los archivos no tengan un tamaño mayor a los 2 kb.
<center></center>
Ahora, como podemos ver, file1 y file2 cumplen con no ser mayores a 2kb. Sin embargo, file3 tiene 8 kb, lo que significará que no pasará la prueba.
En orden de llevar a cabo el código que lleve a cabo la verificación, usamos una función del módulo os llamada listdir, la cual, como su nombre lo indica, crea una lista a partir de los archivos dentro de un directorio.
El único parámetro que nos solicita listdir será la direccion del directorio. Así:
```
import os
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
```
Si imprimimimos el valor resultante:
```
['File1.txt', 'File2.txt', 'File3.txt']
```
Ahora, para determinar el tamaño de cada archivo, aplicamos un ciclo for para recorrer cada elemento de la lista y usamos una de las funciones que vimos en el capítulo anterior:
* os.path.getsize()
Esta nos permite determinar el tamaño de bytes en un archivo, tomando como parámetro la ruta del archivo.
```
import os
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
for file in filelist:
path = os.path.join(dir_path, file)
fileSize = os.path.getsize(path)
```
> Nota: Usamos os.path.join para unir la ruta del directorio con el nombre del archivo en una sola dirección de manera rápida.
Finalmente, usamos otro condicional para verificar si el archivo tiene más de 2000 bytes, obteniendo:
```
##Ejemplo 3
import os
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/testfiles/'
filelist = os.listdir(dir_path)
for file in filelist:
path = os.path.join(dir_path, file)
fileSize = os.path.getsize(path)
if fileSize > 2000:
print(f'{file} has too much info. It will not get transferred')
else:
print(f'{file} verified. It can pass')
>>>
File1.txt verified. It can pass
File2.txt verified. It can pass
File3.txt has too much info. It will not get transferred
```

<center><h2>Ejemplo 4</h2></center>
<center>

<br>[Shoutout to Pi My Life Up](https://pimylifeup.com/python-file-exists/)</center>
Para el último ejemplo, usaremos dos conceptos que hemos visto previamente:
* El manejo de archivos.
* El uso de try except.
Aquí, nos encontramos con indecisión sobre la ruta de un archivo. No recordamos si se encuentra en el directorio principal de nuestra carpeta examplemodules o si se encuentra en el directorio nestedfiles, dentro de la misma carpeta. Para esto, entonces tomaremos las dos rutas.
En primera instancia, buscaremos si el archivo texttowrite.txt se encuentra dentro de examplemodules. En caso de que no esté aquí, buscaremos en nestedfiles.
Para llevar a cabo esto, usaremos el try para el primer caso, donde buscamos en examplemodules y usamos assert, una instrucción que nos permite crear una condición que si se cumple, nos permite ejecutar el programa normalmente. Si el assert no se cumple, nos dará un AssertionError.
Es aquí, donde usamos el AssertionError para el código de nuestro except, donde cambiaremos la ruta y verificaremos de nuevo si existe.
Para poder saber si un archivo existe dentro de un directorio, usamos la función os.path.exists, la cual nos pide como parámetro la ruta del archivo junto con el nombre de este.
Poniendo en práctica todo esto:
```
import os
try:
file = 'texttowrite.txt'
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/'
path = os.path.join(dir_path, file)
result = os.path.exists(path)
assert result == True
print(f'The file {file} is located in {dir_path}')
except:
dir_path = 'C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/nestedfiles/'
path = os.path.join(dir_path, file)
result = os.path.exists(path)
if result == True:
print(f'The file {file} is located in {dir_path}')
else:
raise('The Value is in neither directory')
```
Podemos ver que al final, en orden de verificar si de verdad está en algún archivo, usamos un condicional. En caso de que no se encuentre en ninguno de los dos directorios, nos lo notificará.
Así, si ejecutamos el programa:
```
The file texttowrite.txt is located in C:/Users/rogelio/Desktop/ProyectosPython/examplemodules/nestedfiles/
```
Lo cual es cierto.
<center></center>

Como podrás ver, el familizarnos con os y el manejo de archivos es una tarea sencilla que nos será de gran ayuda a la hora de trabajar con distintos tipos de archivos y manipular la información dentro de estos en módulos posteriores.
Tras esta serie de 3 posts, ya dominarás el file handling, conociéndolo como la palma de tu mano. Es por esto, que en el siguiente post, veremos módulos para el manejo de distintas extensiones.
¡Hemos llegado muy lejos! Date una palmada en la espalda y considerate un estudiante intermedio de ahora en adelante.

<center>¡Gracias por tu apoyo y buena suerte!</center>


</div>