我正在尝试编辑我的csv中的一个列。但是代码似乎不会影响文件。我尝试进行的更改是更改为使用逗号分隔第4列数据。
class Program
{
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv");
var fileContents = ReadFile(filePath);
foreach (var line in fileContents)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public static IList<string> ReadFile(string fileName)
{
var results = new List<string>();
int lineCounter = 0;
string currentLine = string.Empty;
var target = File
.ReadAllLines(fileName);
while ((currentLine = fileName) != null)//while there are lines to read
{
List<string> fielded = new List<string>(currentLine.Split(','));
if (lineCounter != 0)
{
//If it's not the first line
var lineElements = currentLine.Split(',');//split your fields into an array
var replace = target[4].Replace(' ', ',');//replace the space in position 4(field 5) of your array
results.Add(replace);
//target.WriteAllLines(string.Join(",", fielded));//write the line in the new file
}
lineCounter++;
File.WriteAllLines(fileName, target);
}
return results;
}
}
答案 0 :(得分:1)
当前代码有一些错误
最大的一个是currentLine
到fileName
的分配。如果你想循环遍历这一点,这当然没有意义。因此,您需要在读取线上使用foreach
然后在循环内部,您应该使用变量lineElements在分割currentLine
后获得5列。
最后,文件的重写超出了循环范围,应该使用结果列表。
// Loop, but skip the first line....
foreach(string currentLine in target.Skip(1))
{
// split your line into an array of strings
var lineElements = currentLine.Split(',');
// Replace spaces with commas on the fifth column of lineElements
var replace = lineElements[4].Replace(' ', ',');
// Add the changed line to the result list
results.Add(replace);
}
// move outside the foreach loop the write of your changes
File.WriteAllLines(fileName, results.ToArray());
在编写此代码时,我脑海中浮现出一些东西。目前尚不清楚是否要重写CSV文件只包含用逗号扩展的第五列中的数据,或者是否要重写整行(也是第0,1,2,3,4列等等)后一种情况你需要一个不同的代码
// Replace spaces with commas on the fifth column of lineElements
// And resssign the result to the same fifth column
lineElements[4] = lineElements[4].Replace(' ', ',');
// Add the changed line to the result list putting the comma
// between the array of strings lineElements
results.Add(string.Join(",", lineElements);
答案 1 :(得分:1)
while ((currentLine = fileName) != null)
将设置currentLine = fileName,这将使该行始终为true并进行无限循环
我会把它写成for循环而不是一会儿
public static IList<string> ReadFile(string fileName)
{
var target = File.ReadAllLines(fileName).ToList();
// i = 1 (skip first line)
for (int i = 1; i < target.Count; i++)
{
target[4] = target[4].Replace(' ', ','); //replace the space in position 4(field 5)
}
File.WriteAllLines(fileName, target);
// Uncomment the RemoveAt(0) to remove first line
// target.RemoveAt(0);
return target;
}