如何从带分隔符的txt文件中读取文件,并将其写回新的txt文件

How to read file from txt file with delimiters, and write it back to new txt file

例如,我从 txt 文件中获得了数据

Trans ID;Transaction Date;Cashier Name
00001;1 January;Ricky
00001;1 January;Ricky
00002;2 January;Rico

问题是我对这种文件不熟悉,不知道如何读取它并将其导出到具有分离的 Trans ID 的新 txt 文件

所以在这个数据中,会有2个文件,第一个文件是00001 Trans ID的列表,第二个文件是00002文件(或更多trans ID)的列表

我已尝试读取文件

string filename = ("C:\Users\Documents\My Received Files\txn_success_daily.txt");
            string[] lines = File.ReadAllLines(filename);

            foreach (string line in lines)
            {
                string[] col = line.Split(new char[] { ';' });
            }

但我不知道它是如何工作的,因为它不同于 excel(基本上我创建应用程序来生成 excel 文件)

我需要将此数据分成 2 个 txt 文件,因为它包含不同的交易 ID。每一个不同的交易ID,都会创建一个新的txt文件并将交易放入其中(包括header)。

谢谢

// read lines
var lines = File.ReadAllLines(@"D:\Tran.txt");

// group by first value
var groups = lines.Skip(1)
                  .Select(x => x.Split(';'))
                  .GroupBy(x => x[0]);

// iterate groups write the joined lines back to a new file with the key name
foreach (var group in groups)
   File.WriteAllLines($@"D:\Tran{group.Key}.txt", group.Select(x => string.Join(";", x)));

加入胡椒粉和盐调味。

请注意,您最好使用专用的 CSV 解析器,因为这很容易损坏