简体   繁体   English

合并 csv 文件并添加标题行 - 垂直

[英]Combine csv files and add header rows - vertically

I have the following code that combines several csv files and adds file names as headers, but adds them horizontally:我有以下代码组合了几个 csv 文件并将文件名添加为标题,但水平添加它们:

import os
import csv

dir_base = r'H:\apps\xp\Desktop\localrepo\Temp'
dir_name = '-test2'
output_name = 'output.csv'

path = os.path.join(dir_base, dir_name)
out_path = os.path.join(dir_base, output_name)


def _extend(lines, lineno, line):
    try:
        lines[lineno].extend(line)
    except IndexError:
        lines.append(line)


def main():
    lines = []

    # read and generate new file
    for root, dirs, files in os.walk(path):
        for f in files:
            with open(os.path.join(root, f), 'r') as csvfile:
                f_in = csv.reader(csvfile)
                for lineno, line in enumerate(f_in, start=1):
                    if lineno == 1:
                        header = [''] * len(line)
                        header[0] = f
                        _extend(lines, 0, header)
                    _extend(lines, lineno, line)

    # print new file
    with open(out_path, 'w', newline='\n') as csvfile:
        csv.writer(csvfile).writerows(lines)


if __name__ == '__main__':
    main()

This achieves the following output:这实现了以下输出: 在此处输入图片说明

But I want it vertically.但我想要它垂直。 How can I do this ?我怎样才能做到这一点 ?

references: this参考资料: 这个

I managed to merge results vertically using the following script:我设法使用以下脚本垂直合并结果:

def combine_vertically(curr_path, sub):
    with open('%s.csv' % sub, 'w') as wf:
        for subdir, dirss, files in os.walk(curr_path):
            if 'error_metrics_csv' in dirss:
                wf.write("\n")
                wf.write(subdir.split('\\')[-2])
                wf.write("\n")

                # csv_files.append(os.path.join(subdir, 'error_metrics_csv'))
                ptf = os.path.join(subdir, 'error_metrics_csv')
                file = os.path.join(ptf, 'errors.csv')
                with open(file) as rf:
                    for line in rf:
                        if line.strip():  # if line is not empty
                            if not line.endswith("\n"):
                                line = "\n"
                                # line = str(subdir.split('\\')[-1])  "\n"
                            wf.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM