In Python, how to convert a string to a file?

There is a read-only library that takes a file as an argument. But I have a line.

How to convert a string to a file so that, after reading the file, it will return this string? I do not want to write to disk.

+3
source share
2 answers

Module StringIO:

>>> import StringIO
>>> f = StringIO.StringIO("foo")
>>> f.read()
'foo'

The module cStringIOhas the same interface and is faster, but cannot process Unicode strings that have non-ASCII characters.

StringIO Documentation

+15
source

what you need? if you want to read from a file just use:

file('/path/to/file').read()

or

open('/path/to/file','r').read()

if you want to read a line, just do as Phil suggested

0

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


All Articles