你可以使用 Python 的字典数据结构来实现这个任务。首先,将第一个文件的内容读取到字典中,其中字典的键是名字,值是分数。然后,逐行读取第二个文件的内容,如果名字存在于字典中,就用第二个文件的分数替换字典中对应名字的分数。最后,将更新后的字典写入到新的文件中。

下面是一个示例代码:

def compare_files(file1, file2, output_file):
    # 读取第一个文件的内容到字典中
    scores = {}
    with open(file1, 'r') as f1:
        for line in f1:
            name, score = line.strip().split(',')
            scores[name] = score

    # 比较第二个文件的内容并更新字典中的分数
    with open(file2, 'r') as f2:
        with open(output_file, 'w') as output:
            for line in f2:
                name, score = line.strip().split(',')
                if name in scores:
                    scores[name] = score

            # 将更新后的字典写入到新的文件中
            for name, score in scores.items():
                output.write(f'{name},{score}
')

# 示例用法
compare_files('file1.txt', 'file2.txt', 'output.txt')

在上面的示例代码中,file1.txtfile2.txt 是要比较的两个文件,output.txt 是输出的文件。请根据你的实际需求替换这些文件名。此外,假设文件中每行的格式为 name,score,你可以根据实际情况修改代码以适应不同的文件格式。

Python 比较两个文件内容并替换分数 - 代码示例

原文地址: https://www.cveoy.top/t/topic/pArk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录