简体   繁体   English

读取txt文件中的列表并将列表中的每个值输出到新的txt文件python

[英]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 :函数 Diff 是在 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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