0

How can a multi-line string be converted to the type that stdin or an imported file is?

I would like to define a few multi-line strings in the code that can be interpreted as if they were imported from a file or stdin. The reason being I want the text to be in the code and not a separate file.

I would like a solution to the pseudo X = convert(string) below so that the two parse results in the same thing.

input = Open(file.txt)
string = """Hello
             world!"""

X = convert(string)

parse(input)
parse(X)
4

1 回答 1

1

您可以使用io.StringIO

from io import StringIO

string = """Hello
world!"""

X = StringIO(string)
print(X.readlines()) # Example file operation
# ['Hello\n', 'world!']
于 2019-05-12T05:55:32.950 回答