如何使用python将两个文件的内容写入另一个文件

时间:2018-02-06 09:00:58

标签: python file

我有两个文件,其中包含以下内容:

users.txt

Administrator
test_user1
test_user2
test_user3

policies.txt

[a]
[b]
[c]
[d]

我需要交替将这两个文件的内容复制到xls格式的第三个文件中,如下所示:

output.xls

Administrator
[a]
test_user1
[b]
test_user2
[c]
test_user3
[d] 

我这样编码

with open("output.xls", "w") as f3:
    with open("users.txt", "r") as f1:
        with open("policies.txt", "r") as f2:
            for linea1 in f1:
                for linea2 in f2:
                    f3.write(linea1)
                    f3.write(linea2)

output.xls文件以这种方式出现:

Administrator
[a]
Administrator
[b]
Administrator
[c]
Administrator
[d]

我该如何解决?

1 个答案:

答案 0 :(得分:2)

这听起来像你需要zip

with open("output.xls", "w") as f3:
    with open("users.txt", "r") as f1:
        with open("policies.txt", "r") as f2:
            for linea1,linea2 in zip(f1,f2):
                f3.write(linea1)
                f3.write(linea2)

你肯定需要一起写两行。一个来自第一个文件,一个来自第二个。