【问题标题】:Adding values to variables by comparing two files in python通过比较python中的两个文件向变量添加值
【发布时间】:2018-01-26 22:52:27
【问题描述】:

我有两个文本文件。

文件 1: 文件 2: X B 1 0.1 是 3 0.2 Z C 9 0.9 A P 0 0.72 X 2 0.32 是 5 0.89 钾 4 0.17 Z 7 0.59

我想比较 file1 和 file2 并将 file1 的内容和 file2 的第 2 列和第 3 列中的相关数字写入一个新文件。 新文件是:

X 2 0.32 是 5 0.89 Z 7 0.59 一个 3 0.2

我使用 shell 脚本来完成。但我更喜欢基于 python 的脚本来集成到我的其他代码部分。 知道怎么做吗? 提前致谢。

【问题讨论】:

    标签: python


    【解决方案1】:

    这可能有效:

    path1 = 'path/to/file.txt'
    path2 = 'path/to/file.txt'
    path3 = 'path/to/file.txt'
    file1_lines = []
    with open(path1) as file1:
        for lines in file1:
            file1_lines.append(lines)
    
    #remove \n
    file1_lines = list(map(lambda s: s.strip(), file1_lines))
    
    with open(path2) as file2:
        for lines in file2:
            if lines[0:1] in file1_lines:
                with open(path3, 'a') as file3:
                    file3.write(lines)
    

    【讨论】:

    • 太棒了。谢谢。
    • 只是一个问题。如果file1有重复并且我打算在file3中保持顺序和重复不变,如何处理?再次感谢
    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多