【问题标题】:Reading through a list in a txt file and output each value in the list to a new txt file python读取txt文件中的列表并将列表中的每个值输出到新的txt文件python
【发布时间】:2020-11-19 15:52:46
【问题描述】:

所以我有一个脚本,它基本上比较值,然后输出带有最终值的报告。它将它们输出到一个不是我想要的列表中。理想情况下,我希望能够将每个值一个接一个地放在单独的行上。到目前为止,我的代码如下:

    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)

函数 Diff 是在 final-output.txt 中输出以下内容:

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

我希望每个数字都在一行

【问题讨论】:

  • 一个代码块的三个反引号。 Formatting help。请修正你的 python 代码的缩进。
  • for elem in list(set(li2) - set(li1)): f.write(str(elem)+'\n')?

标签: python python-3.x list for-loop


【解决方案1】:

您可以将“Diff”功能代码更改为:

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")

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多