简体   繁体   中英

Reading through a list in a txt file and output each value in the list to a new txt file python

So I have a script which essentially compares values and then output a report with the final values. It outputs them in to a list which is not what I want. Ideally i want to be able to have each value on a separate line one by one. So far my code is as follows :

    def readIntoList(path):
        with open(path, "r") as text1:
            lines = text1.readlines()
            result = []
            for l in lines:
                l_list = l.replace("\n", "").split(" ")
                result.extend(l_list)

        return result

    
    def Diff(li1, li2):
        f = open("final-output.txt", "w")
        f.write(str(list(set(li2) - set(li1))))




    if __name__ == '__main__':
        a = readIntoList('file2.txt')
        b = readIntoList('file3.txt')
        result = Diff(a, b)

The function Diff is what outputs the following in final-output.txt :

['07577930503', '07577930502', '07577930500', '07577985801']

I want each number to be on a single line

You can change your "Diff" function code to:

def Diff(li1, li2):
    f = open("final-output.txt", "w")
    listOfValues = list(set(li2) - set(li1))
    for value in listOfValues:
        f.write(str(value) + "\n")

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