Reading and writing of text files

--Originally published at My B10g

When reading or writing a text file in python you can use the built in library of python to do so. The first step is to open the file and assign it to a variable for practical use (when you open a file you must define what you will be doing with it and to do so you need to use “r” for reading, “w” for writing, “a” appending or “r+”for reading and writing  ) . example:

file = open("hola.txt", 'r')

this mean I want to read file hola.txt

but to get what is in the file you can use:

file.read()

(to read all the file)

file.read(5)

(to read the first 5 characters)

file.readline()

(to read a complete line)

file.readlines()

(to read a list of strings of all the lines in the file)

To write in the file:

file.write("String")

(to write a string in a file)

file.writelines(variable)

(to write a list of strings separated by lines in the file )

When you do it this way you have to close the file at the end to optimize the program:

file.close()

But there are other ways to do it

using (with) there is no need to close the file.

with open("hello.txt", "w") as file:
	file.write("Hello World")

and you can do exactly the same things but writing less code.