c#在CSV文件的末尾添加一列 [英] c# Add a Column to end of CSV file
问题描述
尝试在cvs文件的末尾添加一列,该列将仅计算行数(或者都可以是实际上并不相同的数字),因为主要目的是添加新列里面有一些数据.
Trying to add a column to the end of a cvs file, which will just count up the number of lines (or can all be the same number it doesn't really mater) as the main aim is to add a new column with some data in it.
示例CSV文件有3列,每列中都有一些随机数据.
The sample CSV file I have has 3 columns with some random data in each of them.
我现在所拥有的是
List<string> newColumnData = new List<string>() { "D" };
List<string> lines = File.ReadAllLines(@"C:/CSV/test.csv").ToList();
//add new column to the header row
lines[0] += ",Column 4";
int index = 1;
//add new column value for each row.
lines.Skip(1).ToList().ForEach(line =>
{
//-1 for header
lines[index] += "," + newColumnData[index - 1];
index++;
});
//write the new content
File.WriteAllLines(@"C:/CSV/test.csv", lines);
但是这引发了异常 索引超出范围必须为非负且小于集合的大小"
This however throws up an exception "index was out of range must be nonnegative and less than the size of the collection"
任何建议一如既往地受到欢迎.
Any advice would be most welcome as always.
推荐答案
为什么具体化 ReadAllLines()
,.ToList()
那么多?为什么不只是
Why so many materializations ReadAllLines()
, .ToList()
? Why not just
String filePath = @"C:/CSV/test.csv";
var csv = File.ReadLines(filePath) // not AllLines
.Select((line, index) => index == 0
? line + ",Column 4"
: line + "," + index.ToString())
.ToList(); // we should write into the same file, that´s why we materialize
File.WriteAllLines(filePath, csv);
这篇关于c#在CSV文件的末尾添加一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!