【问题标题】:How to txt file merge using python?如何使用python合并txt文件?
【发布时间】:2017-07-31 15:46:04
【问题描述】:

我有两个 txt 文件。我想使用 python 合并这些文件。 我刚开始学习python,需要一些帮助。我尝试搜索谷歌来解决这个问题,但我找不到解决方案。

所以请帮帮我。

下面是我的两个txt文件。

a.txt 有这个数据。

Zone,alias1,alias2
PA1_H1,PA1,H1
PA2_H2,PA2,H2

b.txt 有这个数据。

WWN,Port,Aliases
da,0,PA1
dq,1,PA2
d2,3,H1
d4,1,H2

预期输出

Zone,alias1,WWN,Port,alias2,WWN,Port
PA1_H1,PA1,da,0,H1,d2,3
PA2_H2,PA2,dq,1,H2,d4,1

我尝试了下面的脚本,但我无法合并。

row = []
for line in open("mod_alias.txt"):
        line = line.split(',')[2]
        row.append(line)

strings = row

for line in open("mod_all_cfgshow.txt"):
        if any(s in line for s in strings):
                field1,field2,field3 = line.split(',')
                print field1,field2,field3

如何合并文件? 你能给我举个例子吗?

【问题讨论】:

  • 合并的标准是什么?基于哪一列?

标签: python dictionary merge output


【解决方案1】:

这里有一些代码可以帮助您入门。此代码将向您展示如何打开这两个文件并将它们合并。然后,您需要做的就是修改代码以使用您喜欢的任何特定规则合并文件。

    # Open Files, read data to lists, and strip data

    with open("b.txt") as bFile:
            bContent = bFile.readlines()
            bContent = [line.strip() for line in bContent]


    with open('a.txt') as aFile:
            aContent = aFile.readlines()
            aContent = [line.strip() for line in aContent]

    # Create a file to store the merged text

    m = open('merged.txt','w')

    # Cycle through the text read from files and merge, and then print to file
    for aLine, bLine in zip(aContent, bContent):

            mergedString = aLine+','+bLine
            print>>m,mergedString

【讨论】:

    【解决方案2】:

    这应该让你开始

    import csv
    
    # read all the data in b.txt into a dictionary, key'd by the alias. We'll look this up later
    data = {}
    with open("b.txt") as infile:
        for row in csv.DictReader(infile):
            alias = row["Aliases"]
            data[alias] = row
    
    with open("a.txt") as fin, open("output.txt", 'w') as fout:
        infile = csv.DictReader(fin)
        outfile = csv.DictWriter(headers=infile.headers+data.keys())
        for row in infile:
            row.update(data[row["Aliases"]]) # update the row with the data from b.txt
            outfile.writerow(row)
    

    【讨论】:

    • 非常感谢。但是你的脚本有错误。 Traceback (most recent call last): File "test7.py", line 12, in <module> outfile = csv.DictWriter(headers=infile.headers+data.keys()) AttributeError: DictReader instance has no attribute 'headers'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2013-10-04
    相关资源
    最近更新 更多