百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

Python 中文件比较和合并的几种有效策略

ztj100 2025-02-18 14:24 35 浏览 0 评论

在日常编程或数据分析任务中,处理比较和合并多个文件是很常见的。Python 具有强大的文件处理能力和广泛的库支持,是处理此类任务的理想选择。

下面,我们将探讨几种有效的文件比较和合并策略,每种策略都附有详细的代码示例和解释。

  1. 基本文件读写

首先,了解如何读取和写入文件是基础。

# Open and read content from the input file
with open('input_file.txt', 'r') as input_file:  
    data = input_file.readlines()  # Read all lines from the input file

# Open the output file and write the content into it
with open('output_file.txt', 'w') as output_file:  
    for line in data:  
        output_file.write(line)  # Write each line to the output file

2. 文件内容比较

使用 difflib 库来比较两个文件之间的差异。

# Import the difflib module for file comparison
import difflib  

# Open and read the first input file
with open('input_file1.txt', 'r') as input_file1, open('input_file2.txt', 'r') as input_file2:
    
    # Compare the content of the two files using unified_diff
    diff = difflib.unified_diff(input_file1.readlines(), input_file2.readlines())
    
    # Print the differences line by line
    print('\n'.join(diff))

3. 合并 CSV 文件

对于 CSV 文件,pandas 库可用于合并操作。

# Import pandas library for data manipulation
import pandas as pd  

# Read the first CSV file into a DataFrame
df1 = pd.read_csv('data_file1.csv')  

# Read the second CSV file into a DataFrame
df2 = pd.read_csv('data_file2.csv')  

# Merge the two DataFrames by concatenating them, assuming matching column names
merged_df = pd.concat([df1, df2], ignore_index=True)  

# Save the merged DataFrame to a new CSV file
merged_df.to_csv('output_merged.csv', index=False)

4. 逐列 CSV 合并

合并特定列,例如基于公共键联接文件。

# Import pandas library for data manipulation
import pandas as pd  

# Read the first CSV file into a DataFrame
df1 = pd.read_csv('data_file1.csv')  

# Read the second CSV file into a DataFrame
df2 = pd.read_csv('data_file2.csv')

# Merge the two DataFrames based on a common column named 'common_key'
# 'how="outer"' ensures that all rows from both DataFrames are included, 
# with missing values filled as NaN where data does not match
merged_df = pd.merge(df1, df2, on='common_key', how='outer')  

# Save the merged DataFrame to a new CSV file
merged_df.to_csv('output_merged_by_key.csv', index=False)  

5. 基于行的合并

当基于相似行结构合并文件时,直接迭代和追加行。

# Initialize an empty list to store the content from all input files
data = []  

# List of input text files to be read and merged
for filename in ['input_file1.txt', 'input_file2.txt']:  
    # Open each file in read mode
    with open(filename, 'r') as file:  
        # Read all lines from the current file and add them to the data list
        data.extend(file.readlines())  

# Open the output file in write mode
with open('output_merged_file.txt', 'w') as merged_file:  
    # Write each line from the data list into the output file
    for line in data:  
        merged_file.write(line)

6. 去重合并

使用 sets 在合并之前删除重复的行。

# Initialize a set to store unique lines from all input files
unique_lines = set()  

# List of input text files to be read and merged
for filename in ['input_file1.txt', 'input_file2.txt']:  
    # Open each file in read mode
    with open(filename, 'r') as file:  
        # Add all lines from the current file to the set (duplicates are automatically removed)
        unique_lines.update(file.readlines())  

# Open the output file in write mode
with open('output_merged_unique.txt', 'w') as merged_file:  
    # Sort the unique lines to ensure consistent output order
    for line in sorted(unique_lines):  
        # Write each unique line into the output file
        merged_file.write(line)

7. 文本文件的二进制比较

使用 filecmp 模块比较文件的二进制内容。

# Import the filecmp module for file comparison
import filecmp  

# Compare the binary contents of 'input_file1.txt' and 'input_file2.txt'
if filecmp.cmp('input_file1.txt', 'input_file2.txt'):  
    print("Files are identical.")  # Output message if files are identical
else:
    print("Files differ.")  # Output message if files differ

8. 大文件高效比对

对于大型文件,请逐行读取和比较它们以节省内存。

# Open the first large file ('input_large_file1.txt') and second large file ('input_large_file2.txt') for reading
with open('input_large_file1.txt', 'r') as f1, open('input_large_file2.txt', 'r') as f2:  
    
# Read lines from both files simultaneously and compare them
    for line1, line2 in zip(f1, f2):  
        # If a difference is found between the two lines, print a message and stop the comparison
        if line1 != line2:  
            print("Difference found!")  
            break  # Exit the loop as the first difference has been found

9. 多个文件的动态合并

使用循环动态合并文件路径列表中的文件。

# Generate a list of file paths for input files ('input_file1.txt' to 'input_file3.txt')
file_paths = ['input_file{}.txt'.format(i) for i in range(1, 4)]  

# Open the output file ('output_merged_all.txt') in write mode
with open('output_merged_all.txt', 'w') as merged:  
    # Iterate through the list of input file paths
    for path in file_paths:  
        # Open each file in read mode
        with open(path, 'r') as file:  
            # Write the content of the current file to the merged output file
            # Add a newline character to separate the content of different files
            merged.write(file.read() + '\n')

10. 高级合并策略:智能合并

对于更复杂的合并标准,例如按日期或 ID 合并,请在合并之前对数据进行排序。

# Import pandas library for data manipulation
import pandas as pd  

# Read CSV files ('input_file1.csv' and 'input_file2.csv') into DataFrames
dfs = [pd.read_csv(f) for f in ['input_file1.csv', 'input_file2.csv']]  

# Concatenate the DataFrames and sort by the 'date_column', assuming it's the column holding the date data
sorted_df = pd.concat(dfs).sort_values(by='date_column')  

# Save the merged and sorted DataFrame to a new CSV file
# Import pandas library for data manipulation
sorted_df.to_csv('output_smart_merged.csv', index=False)  

相关推荐

Docker安全开放远程访问连接权限(docker 远程授权访问)

1、Docker完全开放远程访问Docker服务完全开放对外访问权限操作如下:#开启端口命令(--permanent永久生效,没有此参数重启后失效)firewall-cmd--zone=pu...

SpringCloud系列——4OpenFeign简介及应用

学习目标什么是OpenFeign以及它的作用RPC到底怎么理解OpenFeign的应用第1章OpenFeign简介在前面的内容中,我们分析了基于RestTemplate实现http远程通信的方法。并...

Spring Boot集成qwen:0.5b实现对话功能

1.什么是qwen:0.5b?模型介绍:Qwen1.5是阿里云推出的一系列大型语言模型。Qwen是阿里云推出的一系列基于Transformer的大型语言模型,在大量数据(包括网页文本、书籍、代码等)...

JDK从8升级到21的问题集(jdk8升级到11)

一、背景与挑战1.升级动因oOracle长期支持策略o现代特性需求:协程、模式匹配、ZGC等o安全性与性能的需求oAI新技术引入的版本要求...

大白话详解Spring Cloud服务降级与熔断

1.Hystrix断路器概述1.1分布式系统面临的问题复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。这就造成有可能会发生...

面试突击43:lock、tryLock、lockInterruptibly有什么区别?

在Lock接口中,获取锁的方法有4个:lock()、tryLock()、tryLock(long,TimeUnit)、lockInterruptibly(),为什么需要这么多方法?这些方法都有...

了解网络编程 TCP/IP 协议与UDP 协议

因为iP地址比较难记忆,很多情况下可以使用域名代替iP地址。1.TCP/IP协议与UDP协议通过IP地址与端口号确定计算机在网络中的位置后,接下来考虑通讯的问题:因为不同计算机的软硬件平台...

Semaphore与Exchanger的区别(semaphore和signal)

Semaphore和Exchanger是Java并发编程中两个常用的同步工具类,它们都可以用于协调多个线程之间的执行顺序和状态,但它们的作用和使用方式有所不同:Semaphore类表示一个...

Java教程:什么是分布式任务调度?怎样实现任务调度?

通常任务调度的程序是集成在应用中的,比如:优惠卷服务中包括了定时发放优惠卷的的调度程序,结算服务中包括了定期生成报表的任务调度程序...

java多线程—Runnable、Thread、Callable区别

多线程编程优点:进程之间不能共享内存,但线程之间共享内存非常容易。系统创建线程所分配的资源相对创建进程而言,代价非常小。Java中实现多线程有3种方法:继承Thread类实现Runnable...

工厂模式详解(工厂模式是啥意思)

工厂模式详解简单工厂简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂类的...

我们程序员眼中的母亲节(你眼中的程序员是什么样子的?程序员的薪酬如何?)

导语:对于我们成人来说,尤其是漂泊在外的程序员,陪伴父母的时间太少了。每逢佳节倍思亲,我们流浪外在的游子应该深有感触。母亲,是世界上最伟大的人,她承载着对我们的爱,更是负担和压力。我们作为子女,只会嫌...

死锁的 4 种排查工具(死锁检测方法要解决两个问题)

死锁(DeadLock)指的是两个或两个以上的运算单元(进程、线程或协程),都在等待对方停止执行,以取得系统资源,但是没有一方提前退出,就称为死锁。死锁示例接下来,我们先来演示一下Java中最简...

1. 工厂模式详解(工厂模式示例)

我们的项目代码也是由简而繁一步一步迭代而来的,但对于调用者来说却是越来越简单化。简单工厂模式简单工厂模式(SimpleFactoryPattern)是指由一个工厂对象决定创建出哪一种产品类的实例。...

Jmeter(二十):jmeter对图片验证码的处理

jmeter对图片验证码的处理在web端的登录接口经常会有图片验证码的输入,而且每次登录时图片验证码都是随机的;当通过jmeter做接口登录的时候要对图片验证码进行识别出图片中的字段,然后再登录接口中...

取消回复欢迎 发表评论: