Python自学——多文件数据合并写入新文件(理论上适用于所有,作者这里是TXT文本)

问题:

现有7个文件,如何按照每个文件提取一行数据 进行混合写入新文件?

解题:

import os

filePath=("E:\pycharm\pythonworker\learn/OnlineCard")
osList = os.listdir(filePath)
flist = []
for i in osList:
        if i != 'OnlineCard.txt':
            # print(os.path.splitext(i)[0])
            flist.append(i)
print(flist)
file_ctx = []
for vin_file in flist:
    with open("%s/%s" % (filePath, vin_file), 'r') as f:
        file_ctx.append(f.readlines())

ret_ctx = []
for file_idx in range(0, len(file_ctx)):
    file_ctx[file_idx].reverse()

max_length = [len(x) for x in file_ctx]
max_length = max(max_length)
ofile = open('E:\pycharm\pythonworker\learn/OnlineCard/OnlineCard.txt', 'w+')

j = 1
while j < max_length:
    for file_idx in range(0, len(file_ctx)):
        if len(file_ctx[file_idx]) > 0:
            roll = file_ctx[file_idx].pop()
            if roll is not None:
                ret_ctx.append(roll)
                ofile.write(roll)
    j += 1

# print(ret_ctx)

ofile.close()

 

你可能感兴趣的:(Python,python)