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 a file and then read or write and at last close it. Now let's see how to read or write to a file.

  • Python 2
  • Python 3
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
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.

Let's open a file in read mode.

  • Python 2
  • Python 3
file = open("new","r") #opening 'new'(filename) in 'read' mode
t = file.read() # reading file
print t
file.close()
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 the output. This is because we haven't given any while writing on that file.

'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.

  • Python 2
  • Python 3
file = open("new","r") #opening 'new'(filename) in 'read' mode
t = file.read(2)
print t
t = file.read(999)
print t
file.close()
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 data of other types, the easiest way is to convert them into a string.
For example, write(str([1,2,3]))

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.