Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python io library to write on to an external file

Tags:

python

file-io

I am currently using the python io library to write in to an external file. Below is a sample piece of code which i am trying to execute:

import io
output=io.StringIO
output.write('\n Hello world ')
output.close()
print output.getvalue() 

when I run this piece of code i get an error. Can any one tell me where I am going wrong and whats the reason for the error.

like image 231
Joel James Avatar asked Jan 21 '23 14:01

Joel James


1 Answers

StringIO is for writing to strings, treating them as in-memory streams.

If you want to write to file, do this:

f = open('yourfile', 'w')
f.write('Hello, world.')
f.close()

No need to use StringIO for this.

You did not even get an instance of the class, because there aren't parentheses () after StringIO, so your variable pointed to the StringIO class, and I'm quite sure that is not what you wanted to do.

like image 147
Andrea Spadaccini Avatar answered Mar 15 '23 02:03

Andrea Spadaccini