Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read values one whitespace separated value at a time?

In C++ you can read one value at a time like this:

//from console
cin >> x;

//from file:
ifstream fin("file name");
fin >> x;

I would like to emulate this behaviour in Python. It seems, however, that the ordinary ways to get input in Python read either whole lines, the whole file, or a set number of bits.

I would like a function, let’s call it one_read(), that reads from a file until it encounters either a white-space or a newline character, then stops. Also, on subsequent calls to one_read() the input should begin where it left off.
Examples of how it should work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# file input.in is:
# 5 4
# 1 2 3 4 5
n = int(one_read())
k = int(one_read())
a = []
for i in range(n):
    a.append(int(one_read()))
# n = 5 , k = 4 , a = [1,2,3,4,5]

How can I do this?

>Solution :

Try creating a class to remember where the operation left off.

The __init__ function takes the filename, you could modify this to take a list or other iterable.

read_one checks if there is anything left to read, and if there is, removes and returns the item at index 0 in the list; that being everything until the first whitespace.

class Reader:
    def __init__(self, filename):
        self.file_contents = open(filename).read().split()

    def read_one(self):
        if self.file_contents != []:
            return self.file_contents.pop(0)

Initalise the function as follows and adapt to your liking:

reader = Reader(filepath)
reader.read_one()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading