When a program runs, the data is in the memory but when it ends or computer shuts down, it gets lost. To keep data permanently, we need to write it in a file. Like book, we also need to first open the file and then read or write and at last close it. Now let's see how to read or write to a file.
file = open("new","w") #opening 'new'(filename) in 'write' mode print file file.write("This is first line.") #writing on file file.write("This is second line.") file.close() #closing the file
Here, "w" means that we are opening the file for writing. If there is no file named 'new' then it will create and open one, else it will just open the existing file.
file.close(): closing the file means we are done and now the file will be available for writing. So, let's open in read mode.
file = open("new","r") #opening 'new'(filename) in 'read' mode t = file.read() # reading file print t file.close()
If the given file doesn't exist, then opening in read mode will give you an error.
read() is used to read the file.
Notice that there is no space between "line.This" in output. This is because we haven't given any while writing.
'read()' can also take argument of the number of characters it has to read. If not given any argument as in the above example, it will read till the end.
file = open("new","r") #opening 'new'(filename) in 'read' mode t = file.read(2) print t t = file.read(999) print t file.close()
is is first line.This is second line.
If we give an argument which is more than the number of characters in file, then read will read till the end of the file.