3

Sometimes it would be handy to test a script that reads data from a file using inline data (so that both the data and the code would be in the same file). In bash this can be done with a heredoc:

while read l;do
    echo $l
done << EOF
test
test2
test3
EOF

In some real code there would of course happen something more apart from writing out the lines. Suppose I would do something similar in python:

def read_file(f):
    for line in f.readlines():
        print(line.replace('\n',''))

with open('input.txt') as f:
    read_file(f)

What would be the best way to provide the content of input.txt to read_file() inline?

1 Answer 1

4

You can use StringIO:

from io import StringIO    

f = StringIO('''\
foo
bar
test
''')

read_file(f)

The above code works with Python3. In Python2 use:

from StringIO import StringIO
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.