【发布时间】:2021-03-26 18:54:13
【问题描述】:
我一直在尝试读取包含数字数据的 CSV 文件,这些数据包含文件中 19 列中的每一列的 1000 行。我已经成功地使用当前代码读取单个文件中的每一列并将值添加到小数列表中,但是我收到了一个有趣的用户错误,我似乎无法弄清楚。输出列表仅添加 CSV 文件中一半的值,因此将第二个 for 循环中指定的行范围减半似乎将输出值的数量减半(即 for 循环中指定的 1000 行会导致结果中的 500 个值列表,500 行会在结果列表中产生 250 个值)。代码从函数调用,文件路径作为参数,由 filePath 表示:
'''
If My.Computer.FileSystem.FileExists(filePath) = False Then 'What to do if the file does not exist at the specified path
Throw New Exception("File Not Found: " & filePath) 'Error message if file does not exist
ElseIf My.Computer.FileSystem.FileExists(filePath) = True Then 'What to do if the file does exist at the specified path
Dim fileData = IO.File.ReadAllLines(filePath)
Dim fileColumnCount = (fileData.First.Split(","c).Length) - 1
Dim fileRowCount = fileData.Length
Dim column As Integer
Dim row As Integer
Dim currentColumn As New List(Of Decimal)
column = 0
For column = 0 To fileColumnCount
row = 0
currentColumn.Clear()
For row = 0 To (fileRowCount - 1)
Dim placeholder As String = fileData(row)
Dim currentLine() As String = placeholder.Split(",")
Dim lineList As List(Of String) = currentLine.ToList()
Dim value_dec As Decimal = Convert.ToDecimal(lineList(column))
currentColumn.Add(value_dec)
row += 1
Next
column += 1
Next
End If
End Function
'''
当我在重新启动第一个 for 循环之前使用断点运行程序之后检查 currentColumn(CSV 文件中单个列的输出列表)时,以便只检查第一列,只检查前半部分的值被添加。即使 row 等于 1000 表示每个行值都已被解析,但我总是丢失一半的数据。有什么想法或建议吗?谢谢。
编辑:经过更多测试,输出数据集中似乎没有包含均匀间隔的值。仍然无法解决问题。
【问题讨论】:
-
解析 CSV 文件时,通常会循环行,并为每一行提取其字段的值。不是反过来。我建议至少使用TextFieldParser 类来解析CSV 文件,或者可能更好的是CsvHelper。 -- 在解析文本时寻求帮助时,您应该始终提供该文本的有意义的样本。最好还添加正在使用的 CultureInfo / 语言。
-
如果您的问题已经解决,请考虑accepting the correct answer。
标签: string vb.net list visual-studio csv