使用AutoIt解析循环中CSV文件的所有行 [英] Parse all the rows of a CSV file in a loop using AutoIt
本文介绍了使用AutoIt解析循环中CSV文件的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码来读取包含两行数据的.csv文件.我不知道这是怎么回事.如何改善它以读取包含两行数据的.csv文件?
I have the following code to read a .csv file that contains two rows of data. I do not know what is wrong with it. How can I improve it to read a .csv file with two rows of data?
#include <GUIConstants.au3>
#include <string.au3>
$file = FileOpen("test.csv", 0)
If $file = -1 Then
MsgBox(0, "error", "File doesn't exist or can't be read")
Exit
EndIf
$string = (FileReadLine($file, 1))
$input = StringSplit($string, ",", 1)
$input = StringSplit($string, ",", 1)
Local $value1 = $input[1]
ConsoleWrite("var=" & $value1)
推荐答案
_ParseCSV()的返回值是二维数组,如
return value of _ParseCSV() is 2D array like
$array[1][1] first line first data
$array[1][2] first line second data
$array[3][5] 3rd line 5th data
$array[0][0] gives number of lines
$array[0][1] gives number of data in each line
不需要包含
参数:
- 文件名
- 厚度计
- 如果无法打开文件,则显示消息
- 逻辑真/假可跳过文件的第一行
; _ ParseCSV(文件名",,",发生错误时的消息",true)
;_ParseCSV("filename",",","message if error happens",true)
Func _ParseCSV($f,$Dchar,$error,$skip)
Local $array[500][500]
Local $line = ""
$i = 0
$file = FileOpen($f,0)
If $file = -1 Then
MsgBox(0, "Error", $error)
Return False
EndIf
;skip 1st line
If $skip Then $line = FileReadLine($file)
While 1
$i = $i + 1
Local $line = FileReadLine($file)
If @error = -1 Then ExitLoop
$row_array = StringSplit($line,$Dchar)
If $i == 1 Then $row_size = UBound($row_array)
If $row_size <> UBound($row_array) Then MsgBox(0, "Error", "Row: " & $i & " has different size ")
$row_size = UBound($row_array)
$array = _arrayAdd_2d($array,$i,$row_array,$row_size)
WEnd
FileClose($file)
$array[0][0] = $i-1 ;stores number of lines
$array[0][1] = $row_size -1 ; stores number of data in a row (data corresponding to index 0 is the number of data in a row actually that's way the -1)
Return $array
EndFunc
Func _arrayAdd_2d($array,$inwhich,$row_array,$row_size)
For $i=1 To $row_size -1 Step 1
$array[$inwhich][$i] = $row_array[$i]
Next
Return $array
EndFunc
这篇关于使用AutoIt解析循环中CSV文件的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文