Reading files:
To read a file you should know this functions: open(“filename”,”r”) and filename.read()
The first one is used to open a file, read it and pass that information to a variable ( if you want) or to simply work with it directly.
The second one will just read a file, to use this function ou should have used the open function first like this:
a = open(“filename”) 
print (a.read()) 
As you can see im not using the “r” because that means that i read it at the same time i open it, if you just want to open the file but not read it right there and use that information for later you should do something like what i did above. This has a lot of functionalities if you mix this with strings manipulation. You look for a specific word, count the lines, the total words etc. Here is an aplication for that, this documento opens and reads a file and counts how many times the word “banana” is in it (WSQ14):
def process_file(filename):
    name = open(filename)
    content = name.read()
    list = content.split(” “)
    print (list)
    counter = 0
    for i in list:
        if i.lower() == “banana”:
            counter += 1
    print (counter)
process_file(“file.txt”)

To be sure that this file works correctly i must have a text file named “file” and be sure that each word written in it is separated by a space. If you noticed, reading a file is reading a file is really simple. Is just taking a value from a different file and assigning it to a varible, works like an input. What matters is how you control or process that information.

 Writing a file:
To write a file you have to use the same function as before but this time with a different parameter: open(“filename”,”w”)
This “w” thing will thell python that you want to edit/write the file, be careful because this will erase the content of that file and create a new file. To write a line use fout.write() and use as a parameter a string (or a variable with a string), when you are done use fout.close(). It is very important that you understand that the file will star writing in the last empty line. Here is an example:
 def process_file(filename):
    name = open(“filename”,”w”)

    a = “no”
    while a == “yes”:

       line = input(“Write here the new data”)
       fout.write(line)
       a = input(“want to close?”)
    fout.close() 
process_file(“file.txt”)

This function will add new strings to the “file.txt” document until the user decides to stop.

CC BY 4.0 Mastery30 – Reading and writing files by Jose Carlos Peñuelas Armenta is licensed under a Creative Commons Attribution 4.0 International License.