How to use python io library to write to external file

I am currently using the python io library to write to an external file. The following is sample code that 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 someone tell me where I am wrong and what is the reason for the error.

+3
source share
4 answers

StringIO Designed to write to strings, treating them as threads in memory.

If you want to write to a file, do the following:

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

No need to use StringIOfor this.

, StringIO (), StringIO, , , .

+6

@Andrea. , -:

import cStringIO
output=cStringIO.StringIO()

output.write('\n Hello world ')

print output.getvalue()
output.close()
+2

StringIO, , . , - , :

with open('file/path', 'w') as fh:
    fh.write('Hello World!')

print open('file/path').read() # if you need to actually print it out.
+1

.

. out = io.StringIO().

-, Python v3, write , acsii unicode.

-, , . , StringIO close. , Java, (StringWriter) .

Finally, StringIO writes to memory, not to a file. Use out = open(filename,'w')if you want to write to a file.

So, not knowing the exact error you received, that is all that I received. The error message you get is usually quite helpful.

0
source

Source: https://habr.com/ru/post/1790024/


All Articles