WSQ09 – Files

--Originally published at Elu's Blog

For this assignment these were my instructions:

So for this assignment I would like to see you create a function that receives as parameter the name of a file (this would be a string value like data.txt) and your function counts the number of lines and the number of characters in the file which it returns as a single value (but with two values). You will want to look at how to use and return a tuple from a function and how to open and read text files line by line.

This is what I came up with:

Captura de pantalla 2017-03-06 a la(s) 10.39.34.png

Captura de pantalla 2017-03-06 a la(s) 10.31.38.png

Captura de pantalla 2017-03-06 a la(s) 10.39.48.png

Reading and writing of text files

When using external files in python, there are a few things that can be done to it: read, write, append and the binary versions of the previous three.

To use a file, you have to first  open it with the open() function. open(‘[fileaddress]’,'[opening mode]’ <- this is how to use the function. One example is:

f = open(‘/Users/rafaelelu/Desktop/Tec/Primer Semestre/Fundamentos de Programación (Ken Bauer)/46 Simple Python Exercises/’text.txt’,’r’) <- This will open the ‘text.txt’ file in read mode.

‘r’ = read mode ‘rb’ = read in binary mode

‘w’ = write mode   ‘wb’ = write in binary mode

‘a’ = append mode   ‘ab’ = append in binary mode

Note: when opening a file in write mode, all of its text will be deleted previous to writing on it. Also if you open a file (in write mode) that doesn’t exist, it will create a file with that name in the same address as the programmed.

In my code above, I used ‘txt =’ in line 4. This assigns all characters of the file in the txt variable. To write in a file, use the .write() function and inside the parenthesis write

Continue reading "WSQ09 – Files"