Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap a string in a file in Python?

How do I create a file-like object (same duck type as File) with the contents of a string?

like image 944
Daryl Spitzer Avatar asked Sep 26 '08 19:09

Daryl Spitzer


People also ask

How do you wrap a string in Python?

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

How do you align text in Python?

You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.

How do you create a file like an object in Python?

To create a file object in Python use the built-in functions, such as open() and os. popen() . IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.


1 Answers

For Python 2.x, use the StringIO module. For example:

>>> from cStringIO import StringIO >>> f = StringIO('foo') >>> f.read() 'foo' 

I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)

For Python 3.x, use the io module.

f = io.StringIO('foo') 
like image 153
Daryl Spitzer Avatar answered Oct 06 '22 05:10

Daryl Spitzer