Saturday, 5 December 2015

Python: Write data to file

Python provides following methods to write data to a file.

write (): Used to write a fixed sequence of characters to a file. Return number of characters written to file.

writelines(): writelines can write a list of strings.
>>> f=open("/Users/harikrishna_gurram/data.txt", 'w')
>>> 
>>> f.write("Hello, How are you\n")
19
>>> f.write("I am fine, How is u\n")
20
>>> data=["first line\n", "second line\n"]
>>> f.writelines(data)
>>> f.close()
>>> 
>>> f=open("/Users/harikrishna_gurram/data.txt")
>>> for line in f:
...     print(line, end='')
... 
Hello, How are you
I am fine, How is u
first line
second line


‘write’ method only accepts string argument. If you try to insert non-string data, you will get TypeError.

>>> f=open("/Users/harikrishna_gurram/data.txt", 'w')
>>> f.write(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not int

To write something other than a string, it needs to be converted to a string first. By using ‘str’ function, you can convert non string data to string.  

>>> a=123.45
>>> temp=str(a)
>>> temp
'123.45'
>>> 
>>> f=open("/Users/harikrishna_gurram/data.txt", 'w')
>>> f.write(temp)
6
>>> 
>>> f.close()
>>> 
>>> f=open("/Users/harikrishna_gurram/data.txt")
>>> f.read()
'123.45'



Previous                                                 Next                                                 Home

No comments:

Post a Comment