1

Using a C/C++ analogy, I want to pipe the contents of a file to stdin.

I have a Python function that prompts users for student name and grade and creates a list of lists. Instead of typing a 100 names and grades, I want to put the names and grades in a text file and provide that as input to this function. How do I do this? Code fragment below:

def enter_grades(num_students):
    class_grades = []
    for i in range(num_students):
       class_grades.append([input(), float(input())])
    print( class_grades)
    return class_grades

There is a file "grades.txt" with student names and grades. Want to provide its contents as input to enter_grades().

1
  • 1
    I want to use the file to test the function with a lot of inputs. Commented Dec 30, 2017 at 1:35

1 Answer 1

2

You are finding the python version of freopen().

You can set the sys.stdin to a file object simply do the following:

import sys

sys.stdin = open("/path/to/file.txt", "r")
text = input()
print(text)

The input() function will now read data from file instead of user input.

More Usage

Similarly, if you want to redirect the standard output or standard error to a file, just set the corresponding variables in sys:

sys.stdout = open("stdout.txt", "w")
sys.stderr = open("stderr.txt", "w")
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.