简体   繁体   中英

How to read integers from text file and put them in a list in python?

I'm creating a class which takes data from text files. Every file is composed by 3 integers each line and indefinite lines, like the following example:

1 3 5

3 13 8

4 5 10

... Let's say this data is in a file called 'numbers.txt'. How can I put this 3 integers in a tuple, and then this tuple, in a list of tuples?

This is what I currently have (obviously wrong):

def _create_from_file(self, sky):
        """From a list of integers in a file, creates a list of tuples"""
        self.sky = sky
        f = open(self.sky)
        self.numbers=[]
        for line in open(self.sky):
            self.numbers.append((line[0],line[1],line[2]))

This should work:

def _create_from_file(self, sky):
    """From a list of integers in a file, creates a list of tuples"""
    self.sky = sky
    with open(self.sky, 'r') as f:
        self.numbers = [ tuple(int(x) for x in line.strip().split()) for line in f ]

If your numbers are floats rather than integers, replace int with float .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM