logo codesdope

File i/o in Python


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
Output
<open file 'new', mode 'w' at 0x7fa2cedd4540>

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()
Output
This is first line.This is second line.

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()
Output
Th
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.

If we will write something on a file which is opened in write ('w') mode, then its previous content gets deleted and the new content is written from the beginning of the file. To write from the end of the previously written content, we open the file in append mode ('a').
The argument of write() must be a string. So to give other things, the easiest way is typecasting.
eg.- write(str([1,2,3]))
Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.