在Python中按行合并几个文本文件



我是trade的网络工程师,新的python,这个问题将应用于路由器上的访问列表,但为简单起见,我将使用州和城市。

我有几个文本文件(下面两个),其中包含状态和城市行,如下所示:

file1

Texas
Austin
Dallas
Houston
San Antonio

file2

Texas
Amarillo
Austin
Dallas
San Antonio
Waco

我需要合并这两个文件,并吐出一个看起来像下面一个的新文本文件:

Texas
Amarillo
Austin
Dallas
Houston
San Antonio
Waco

必须精确地定位,因为与File2相比,File1缺少Amarillo,并且File2在Austin顶部具有Amarillo,然后合并的文件将在由此产生的文件中的Austin或Texas下方的Amarillo。如果与File1相比,File2缺少某些城市的情况下,则适用同一件事。

我不太确定如何启动此脚本。引导将不胜感激!

谢谢!

这是一种简单的方法:

#! /usr/bin/python3
from sys import exit

def w(data, title):
    with open('f3.txt', 'w') as file_out:
        file_out.write(title + 'n')
        for line in data:
            file_out.write(line + 'n')
def r(path):
    with open(path) as file_in:
        lines = file_in.read().split('n')
    return [l for l in lines if l]

def combine(path1, path2):
    f1 = r(path1)
    f2 = r(path2)
    title1 = f1.pop(0)
    title2 = f2.pop(0)
    # ensure Texas is the first line in each file
    if title1 != title2:
        print("Titles do not match")
        exit()
    w(sorted(set(f1 + f2)), title1)

if __name__ == "__main__":
    combine('f1.txt', 'f2.txt')

这是运行前后的目录/文件内容:

james@rootVIII:~/Desktop$ ls
delete  f1.txt  f2.txt  test.py  utils
james@rootVIII:~/Desktop$ 
james@rootVIII:~/Desktop$ cat f1.txt 
Texas
Austin
Dallas
Houston
San Antonio
james@rootVIII:~/Desktop$ 
james@rootVIII:~/Desktop$ cat f2.txt 
Texas
Amarillo
Austin
Dallas
San Antonio
Waco
james@rootVIII:~/Desktop$ 
james@rootVIII:~/Desktop$ ./test.py 
james@rootVIII:~/Desktop$ 
james@rootVIII:~/Desktop$ 
james@rootVIII:~/Desktop$ cat f3.txt 
Texas
Amarillo
Austin
Dallas
Houston
San Antonio
Waco

有些要注意的事情:

  1. 这将期望"德克萨斯州"或状态名称是每个文本文件中的第一个条目(f1.txt和f2.txt)

  2. 将列表变成集合删除重复

  3. 组合()方法可以接受相对或绝对路径

  4. 列表理解[l for l in lines if l]返回一个没有空元素的列表(因为字符串是用newline拆分的)...如果在Whitespace上分开,您将获得SAN而不是San Antonio

最新更新