-1

2 行のデータを含む .csv ファイルを読み取る次のコードがあります。何が悪いのかわかりません。2 行のデータを含む .csv ファイルを読み取るように改善するにはどうすればよいですか?

#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)
4

3 に答える 3

2

_ParseCSV() の戻り値は のような 2D 配列です

$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

インクルードは必要ありません

パラメータ:

  1. ファイル名
  2. デリメータ
  3. ファイルが開けない場合のメッセージ表示
  4. ファイルの最初の行をスキップする論理 true/false

;_ParseCSV("ファイル名",",","エラー発生時のメッセージ",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
于 2013-12-14T21:00:16.600 に答える
0

これは、2行のCSVファイルを読み取り、両方のデータフィールドを出力するプログラムです。行数が多い場合は、入力配列を大きく変更してください。

#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

   ; Read in lines of text until the EOF is reached
While 1
    Local $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
   $input = StringSplit($line, ",")

   ;This is reading fields 1 and 2. 
   ;The array index [0] 
   ;it will tell you how big the array is.
   Local $value1 = $input[1]
   Local $value2 = $input[2]
   ConsoleWrite("var=" & $value1)
   ConsoleWrite("var=" & $value2)

WEnd
于 2012-12-19T01:18:03.380 に答える