在python3中将列表写入文本文件

时间:2018-01-21 17:14:40

标签: python python-3.x list

我需要读取3个txt文件并将它们合并为一个大的txt文件。

Ex text file1:

John
Mary
Joe

前文字文件2:

Alabama
Alaska
Michigan

Ex text file3:

Maybe
Attending
Not Attending

我不确定还有什么要添加到我的代码中

path = '/home/pi/Documents/Test/name.txt'
file1 = open (path, 'r')
name = file1.read()

statepath = '/home/pi/Documents/Test/state.txt'
file2 = open (path, 'r')
states = file2.read()

statuspath = '/home/pi/Documents/Test/status.txt'
file3 = open(statuspath, 'r')
status = file3.read()

finalpath = '/home/pi/Documents/Test/final.txt'
file4 = open(finalpath, 'w')
final = file4.read()


for item in name, states, status:
    final.write(file1, "\n")
    final.write(file2, "\n")
    final.write(file3, "\n")

file1.close()
file2.close()
file3.close()
final.close()

文件的最终预期输出是

John  <------- first value in file1
Alabama <------ first value in file2
Maybe  <------- first value in file 3
Mary  <---------- second value in file 1
Alaska
Attending
Joe
Michigan
Not Attending

基本上尝试遍历所有这些并按顺序打印它们 不知道如何循环。

4 个答案:

答案 0 :(得分:1)

首先,你正在写决赛而没有真正读过任何东西,所以它无法正常工作。将file1file2file3替换为具有read()属性的变量。

只需对要循环的每个变量使用for语句。像这样:

for i in name:
    for j in states:
        for k in status:
            all = i + '\n` + j + '\n' + k + '\n' 

final.write(all)

答案 1 :(得分:1)

可能的解决方案之一,但您应该确保3个文件的长度相同。

def main():
    name_path = 'name.txt'
    state_path = 'state.txt'
    status_path = 'status.txt'
    final_path = 'final.txt'
    with open(name_path, 'r') as file1, open(state_path, 'r') as file2, open(status_path, 'r') as file3, open(final_path, 'w') as final:
        for line in file1.readlines():
            final.write(line)
            final.write(file2.readline())
            final.write(file3.readline())

答案 2 :(得分:0)

使用itertools执行此操作的一些方法:

import itertools as it
files = [
    '/home/pi/Documents/Test/name.txt',
    '/home/pi/Documents/Test/state.txt',
    '/home/pi/Documents/Test/status.txt'
]

def loadData(fpath):
    with open(fpath, "r") as f:
        yield from f.redlines()

with open('/home/pi/Documents/Test/final.txt') as f:
    for e in it.chain.from_iterable(zip(*map(loadDAta, files))):
        f.write(e)

答案 3 :(得分:0)

我只是稍微改进了Netwave版本,它似乎是解决此任务的正确pythonic方式,完整代码将是这样的

import itertools as it


def load_data(fpath):
    with open(fpath, 'r') as f:
        for line in f.readlines():
            yield line


def main():
    files = [
        '/home/pi/Documents/Test/name.txt',
        '/home/pi/Documents/Test/state.txt',
        '/home/pi/Documents/Test/status.txt'
    ]

    with open('/home/pi/Documents/Test/final.txt', 'w') as f:
        for e in it.chain.from_iterable(zip(*map(load_data, files))):
            for line in e:
                f.write(line)


if __name__ == '__main__':
    main()