合并两个文本文件的内容
来源:互联网 发布:看门狗win10优化补丁 编辑:程序博客网 时间:2024/05/17 22:13
1. 需求
把两个文本文件的内容合并到一个文件中,且并不要求文件中行的顺序保持不变。
且适用于两个文本文件中有较多的数据是完全一样的,仅存在少量不一致的地方。
2. 方案
因为两个文本文件中的存在
把两个文件的内容读到list中,然后再转换成set类型,最后取并集即可。
3. 实现代码
def merge_text_file(first_filename, second_filename, merged_filename): ''' Merge two text files, the sequence of two file's content maybe changed. example: source_file_1 = "a.txt" source_file_2 = "b.txt" merged_file = "merged.txt" merge_text_file(source_file_1, source_file_2, merged_file) ''' first_list = open(first_filename, 'r').read().split('\n') second_list = open(second_filename, 'r').read().split('\n') result_set = set(first_list) | set(second_list) result_list = list(result_set) result_list.sort() result_file = open(merged_filename, "w") for item in result_list: temp = item.strip() if temp == "": continue result_file.write(temp + '\n') result_file.close()
4. 使用示例
import file_utilitiesdef _write_temp_file(filename, values): f = open(filename, "w") for value in values: f.write(value + '\n') f.close()def _test(): first_values = ["first", "second"] second_values = ["first", "third"] first_filename = "first_abcdefghijklmn.xyz" second_filename = "second_abcdefghijklmn.xyz" merged_filename = "merged_abcdefghijklmn.xyz" _write_temp_file(first_filename, first_values) _write_temp_file(second_filename, second_values) file_utilities.merge_text_file(first_filename, second_filename, merged_filename) # assert the result result = open(merged_filename, "r").read().split('\n') result.remove('') print "result:", result result = set(result) expected_result = set(['first', 'second', 'third']) print "expected result:", expected_result if result == expected_result: print "PASS" else: print "FAIL"if __name__ == '__main__': _test()
运行结果:
D:\examples\python\file_utilities>python test_merge_text_file.pyresult: ['first', 'second', 'third']expected result: set(['second', 'third', 'first'])PASSD:\examples\python\file_utilities>
0 0
- 合并两个文本文件的内容
- Dos命令将两个文本文件内容合并
- linux合并两个文本文件
- eclipse 比较两个文本文件的 内容
- shell中把一个文本文件列的内容合并成行
- Qt两个文件的内容合并
- 合并内容格式不同的两个文件
- 合并两个文件的内容:shell/java
- DOS命令比较两个文本文件txt的内容差异
- 用perl实现两个文本文件交叉合并
- 合并两个文件,并且排除掉重复的内容
- Java源码-将多个文本文件的内容合并为一个文件的Java实现
- Python实现文本文件的合并
- 提取txt文本文件里的内容分别放到两个文件中
- 在windows命令行(cmd)下,如何合并两个文本文件
- 合并多个文本文件中的内容到一个文件中
- java编程之合并两个文件内容
- Excel如何合并两个单元格内容
- 两道基础线段树简解:HDU 1166 敌兵布阵,HDU 1754 I Hate it
- 2014 青年歌手大奖赛_评委会打分
- 数钱问题
- UVA 10115(字符串)
- test
- 合并两个文本文件的内容
- MFC picture 控件error RC2108: expected numerical dialog constant
- hdu oj 统计字符 题目1860
- 学习之:oracle的start with..connect by prior
- Java TCP通信(服务器和客户端代码)
- 配置pl/sql远程访问服务器数据库
- Android生成随机验证码
- HDU 1271 整数对-组合数学
- ionic的header颜色设置