如何将两个csv文件与公共头合并 [英] How to merge two csv files with common header

查看:131
本文介绍了如何将两个csv文件与公共头合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下格式的csv文件。

Hi,
I have a csv file in the following format.

col1  col2
a      aa
b      ba
CSV    file 2
col1   col2
c      a
d      b

Final OutPut:
col1  col2
a     aa
b     ba
c     a
d     b



我的代码是:


My code is:

var fiels = new DirectoryInfo(Source).GetFiles("*_*.csv")

             .OrderBy(f => f.CreationTime);


             var fileGroups = (from file in fiels group file.Name by file.Name.Substring(0, file.Name.IndexOf('_', 1)));


             foreach (var g in fileGroups)
             {
                 string newFileName = g.Key + ".csv";
                 string newfileContent = "";
                 foreach (var f in g)
                 {
                     newfileContent +=
                             System.IO.File.ReadAllText(System.IO.Path.Combine(Source, f));

                     count++;
                 }

                 System.IO.File.WriteAllText(System.IO.Path.Combine(To_be_processed, newFileName),
                                                newfileContent);

             }





我的输出是



My output is

col1  col2
a      aa
b      ba
col1  col2
c      a
d      b



如何在合并时获得共同的听众?


How can i get common hearder while merging?

推荐答案

if (newfileContent == "")
                        {
                            newfileContent +=
                                    System.IO.File.ReadAllText(System.IO.Path.Combine(Source, f));
                        }
                        else
                        {
                            using (StreamReader Read = new StreamReader(Source + "\\" + f))
                            {
                                string Header = Read.ReadLine();
                                while ((line = Read.ReadLine()) != null)
                                {
                                    newfileContent += line;
                                    newfileContent += Environment.NewLine;

                                }
                            }
                        }


这篇关于如何将两个csv文件与公共头合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆