Search code examples
pythonpython-3.xlistappendreadfile

Why won't this function append values from the textfile to my list?


def read1(file):                #this function will read and extract the first column of values from the
    with open(file,"r") as b:        # text allowing us to access it later in our main function
        list1 = list(b)
        lines = b.readlines()
        result1 = []
        for i in lines:
            result1.append(list1.split()[0])
    b.close
    return result1
x = read1("XRD_example1.txt")

Any errors clearly visible?


Solution

  • You do:

        list1 = list(b)
        lines = b.readlines()
    

    but the first of those lines already reads up all contents of your file, there's nothing to be read in the second line.

    def read1(file):                #this function will read and extract the first column of values from the
        with open(file,"r") as b:        # text allowing us to access it later in our main function
            lines = b.readlines()
            result1 = []
            for i in lines:
                result1.append(i.split()[0])
        # no need for close, when using 'with open()'
        return result1
    

    should work, or even better:

    def read1(file):                
        with open(file,"r") as b: 
            return [i.split()[0] for i in b.readlines()]