Jump to content

I don't fully understand StringSplit


johnm
 Share

Recommended Posts

My ultimate goal: Take a CSV file one record at a time, assign each section (in between the comma's) to a variable and then put each variable into a field/text box onto a web page, look for certain text to document, record it, go back to the page to enter the next line of information from the csv file.

I'm taking this one step at a time. I'm able to open a csv file and read one record at a time but the part I'm stuck on is I can't seem to break it up to show me the information between the comma's. The closest I come is to getting the whole line/record at one time.

When I run the following code, it gets stuck and shows me a window over and over again and never stops. I have to end task on it.

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    $portion = StringSplit($file,",")
    $value1 = $portion[0]
    If @error = -1 Then ExitLoop
    MsgBox(0, "Line read:", $value1)
Wend

FileClose($file)

mc.csv contains...

05008008,1234567980,01012008,01102008,01311940,DUCK,DAFFY,123445678

05008008,1234567890,01012008,01132008,01101939,MOUSE,MINNIE,987665432

When I run the following code, I see each line just fine in the message box but I need each line split up to assign a variable to each section.

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    MsgBox(0, "Line read:", $line)
Wend

FileClose($file)

I've googled for about 3-4 hours now and I'm not finding any good examples. I came across this page where a user by the name of kunchi and it looks like they were asking the same thing but the answer given didn't really help.

http://otland.net/f134/autoit-script-read-csv-file-execute-commands-28716/

Link to comment
Share on other sites

My ultimate goal: Take a CSV file one record at a time, assign each section (in between the comma's) to a variable and then put each variable into a field/text box onto a web page, look for certain text to document, record it, go back to the page to enter the next line of information from the csv file.

I'm taking this one step at a time. I'm able to open a csv file and read one record at a time but the part I'm stuck on is I can't seem to break it up to show me the information between the comma's. The closest I come is to getting the whole line/record at one time.

When I run the following code, it gets stuck and shows me a window over and over again and never stops. I have to end task on it.

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    $portion = StringSplit($file,",")
    $value1 = $portion[0]
    If @error = -1 Then ExitLoop
    MsgBox(0, "Line read:", $value1)
Wend

FileClose($file)

mc.csv contains...

05008008,1234567980,01012008,01102008,01311940,DUCK,DAFFY,123445678

05008008,1234567890,01012008,01132008,01101939,MOUSE,MINNIE,987665432

When I run the following code, I see each line just fine in the message box but I need each line split up to assign a variable to each section.

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    MsgBox(0, "Line read:", $line)
Wend

FileClose($file)

I've googled for about 3-4 hours now and I'm not finding any good examples. I came across this page where a user by the name of kunchi and it looks like they were asking the same thing but the answer given didn't really help.

http://otland.net/f134/autoit-script-read-csv-file-execute-commands-28716/

Hi,

change your while loop to:

While 1
    $line = FileReadLine($file)
    $portion = StringSplit($line,","); changed $file to $line
    If @error = -1 Then ExitLoop
    For $i = 1 To $portion[0]; portion[0] contains number of strings in array portion
        MsgBox(0, "Line read:", $portion [$i])
    Next
Wend

;-))

Stefan

Link to comment
Share on other sites

$file = FileOpen(@ScriptDir & "\mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    $portion = StringSplit($line,",")
    $txt = ""
    For $i = 1 To $portion[0]
        $txt &= "value" & $i & "=" & $portion[$i] & @CRLF
    Next
    MsgBox(262144 +48, "", $txt)
Wend

FileClose($file)

I would just use the array elements of $portion directly rather than assigning to a variable.

Link to comment
Share on other sites

Hi,

change your while loop to:

While 1
    $line = FileReadLine($file)
    $portion = StringSplit($line,","); changed $file to $line
    If @error = -1 Then ExitLoop
    For $i = 1 To $portion[0]; portion[0] contains number of strings in array portion
        MsgBox(0, "Line read:", $portion [$i])
    Next
Wend

;-))

Stefan

Hi Stefan,

I ran your code and the messagebox just comes up blank and I have to end task on it. Thanks for the feedback though.

Link to comment
Share on other sites

$file = FileOpen(@ScriptDir & "\mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    $portion = StringSplit($line,",")
    $txt = ""
    For $i = 1 To $portion[0]
        $txt &= "value" & $i & "=" & $portion[$i] & @CRLF
    Next
    MsgBox(262144 +48, "", $txt)
Wend

FileClose($file)

I would just use the array elements of $portion directly rather than assigning to a variable.

Hi Picaxe,

When I run your code, I don't get any message box. (It doesn't look like anything happens) Thanks for the response though.

Link to comment
Share on other sites

Hi Picaxe,

When I run your code, I don't get any message box. (It doesn't look like anything happens) Thanks for the response though.

You aren't doing something right and if you don't show what you've tried then we can't say what.

Try this

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
$lcount = 1
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    $Aline = stringsplit($line,",")
    MsgBox(0, "Line read:", $line)
    for $n = 1 to $aline[0]
        msgbox(262144,"item " & $n & " of line " & $lcount, $aline[$n])
    Next
    $lcount += 1
Wend

FileClose($file)
Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.
Link to comment
Share on other sites

  • Moderators

I've done this somewhere before, but can't remember where.

Anyway, this isn't exactly what you asked for, but it will return a 2 dimensional array where [0][0] = the total number of lines, [n][x] where n = the line, and x = each individual delimited text.

#include <array.au3>

Global $a_vals = _File_Delimiter_GetArray("somefile.csv", ",")
_ArrayDisplay($a_vals)

Func _File_Delimiter_GetArray($s_file, $s_delimiter = ",")
    Local $s_str = $s_file
    If FileExists($s_file) Then $s_str = FileRead($s_file)
    
    Local $a_lines = StringSplit(StringStripCR($s_str), @LF)
    Local $a_ret_array[$a_lines[0] + 1][1], $a_delim, $i_add = 0
    
    For $i = 1 To $a_lines[0]
        If $a_lines[$i] = "" Then ContinueLoop
        
        $a_delim = StringSplit($a_lines[$i], $s_delimiter, 1)
        
        $i_add += 1
        
        If $a_delim[0] > UBound($a_ret_array, 2) - 1 Then
            ReDim $a_ret_array[$a_lines[0] + 1][$a_delim[0] + 1]
        EndIf
        
        For $j = 1 To $a_delim[0]
            $a_ret_array[$i_add][$j] = $a_delim[$j]
        Next
    Next
    
    If $i_add = 0 Then Return SetError(1, 0, 0)
    ReDim $a_ret_array[$i_add + 1][UBound($a_ret_array, 2)]
    
    $a_ret_array[0][0] = $i_add
    
    Return $a_ret_array
EndFunc

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

You aren't doing something right and if you don't show what you've tried then we can't say what.

Try this

Hi Martin, I took Stephan's while loop and put it in place of mine from my above example. I took Picaxe's code and ran it as is. I tried your code as is. Nothing is happening when I run yours, the code from Picaxe and SmOke_N. I built the code and tried to run it. Nothing comes up at all. I get a really fast hour glass which goes away and there is no resulting message box that pops up.

I've done this somewhere before, but can't remember where.

Anyway, this isn't exactly what you asked for, but it will return a 2 dimensional array where [0][0] = the total number of lines, [n][x] where n = the line, and x = each individual delimited text.

SmOke_N, I tried your code and I can't seem to get a message box to come up.

I'm running AutoIT on Vista64, does anyone know of any issues with that platform? When I run the following code, I at least get a message box but I have to end task on it to clear it...

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
    $line = FileReadLine($file)
    $portion = StringSplit($line,","); changed $file to $line
    If @error = -1 Then ExitLoop
    For $i = 1 To $portion[0]; portion[0] contains number of strings in array portion
        MsgBox(0, "Line read:", $portion [$i])
    Next
Wend

FileClose($file)

I'll keep googling but if anyone has fixed this problem, I'd very much welcome the solution you used.

Link to comment
Share on other sites

  • Moderators

If you're trying to read a file in the program files directory, you'll fail more than likely.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

When I run the following code, it gets stuck and shows me a window over and over again and never stops. I have to end task on it.

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    $portion = StringSplit($file,",")
    $value1 = $portion[0]
    If @error = -1 Then ExitLoop
    MsgBox(0, "Line read:", $value1)
Wend

FileClose($file)
It looks like the reason it is getting "stuck" is the "If @error = -1 Then ExitLoop" is in the wrong spot, it has to come immediately after the "$line = FileReadLine($file)", since it is the "FileReadLine" that you are checking the error on. Being that you have it after "$value1 = $portion[0]", the error wouldn't be -1 so it never leaves...

$file = FileOpen("mc.csv", 0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf

While 1
    $line = FileReadLine($file)
    $portion = StringSplit($line,","); changed $file to $line
    If @error = -1 Then ExitLoop
    For $i = 1 To $portion[0]; portion[0] contains number of strings in array portion
        MsgBox(0, "Line read:", $portion [$i])
    Next
Wend

FileClose($file)

This looks good but seems to have the same issue, try moving @error and see what happens.

Ian

My projects:

  • IP Scanner - Multi-threaded ping tool to scan your available networks for used and available IP addresses, shows ping times, resolves IPs in to host names, and allows individual IPs to be pinged.
  • INFSniff - Great technicians tool - a tool which scans DriverPacks archives for INF files and parses out the HWIDs to a database file, and rapidly scans the local machine's HWIDs, searches the database for matches, and installs them.
  • PPK3 (Persistent Process Killer V3) - Another for the techs - suppress running processes that you need to keep away, helpful when fighting spyware/viruses.
  • Sync Tool - Folder sync tool with lots of real time information and several checking methods.
  • USMT Front End - Front End for Microsoft's User State Migration Tool, including all files needed for USMT 3.01 and 4.01, 32 bit and 64 bit versions.
  • Audit Tool - Computer audit tool to gather vital hardware, Windows, and Office information for IT managers and field techs. Capabilities include creating a customized site agent.
  • CSV Viewer - Displays CSV files with automatic column sizing and font selection. Lines can also be copied to the clipboard for data extraction.
  • MyDirStat - Lists number and size of files on a drive or specified path, allows for deletion within the app.
  • 2048 Game - My version of 2048, fun tile game.
  • Juice Lab - Ecigarette liquid making calculator.
  • Data Protector - Secure notes to save sensitive information.
  • VHD Footer - Add a footer to a forensic hard drive image to allow it to be mounted or used as a virtual machine hard drive.
  • Find in File - Searches files containing a specified phrase.
Link to comment
Share on other sites

  • Moderators

I have this line in my code...

$file = FileOpen("mc.csv", 0)

The mc.csv file is in the same directory as the script. I've even tried...

$file = FileOpen("c:\scripts\mc.csv", 0)

...and that didn't work.

You're bordering rediculous with the amount of information you provide.

Run my post I provided just like this:

#include <array.au3>
Global $s_my_csv_file = "c:\scripts\mc.csv"

If FileExists($s_my_csv_file) = 0 Then
    MsgBox(16, "Error", "Duh!")
    Exit
ElseIf FileRead($s_my_csv_file) = "" Then
    MsgBox(16, "Error", "Either the directory your script is in is protected, or your file is blank!")
    Exit
EndIf

Global $a_vals = _File_Delimiter_GetArray($s_my_csv_file, ",")
_ArrayDisplay($a_vals)

Func _File_Delimiter_GetArray($s_file, $s_delimiter = ",")
    Local $s_str = $s_file
    If FileExists($s_file) Then $s_str = FileRead($s_file)
    
    Local $a_lines = StringSplit(StringStripCR($s_str), @LF)
    Local $a_ret_array[$a_lines[0] + 1][1], $a_delim, $i_add = 0
    
    For $i = 1 To $a_lines[0]
        If $a_lines[$i] = "" Then ContinueLoop
        
        $a_delim = StringSplit($a_lines[$i], $s_delimiter, 1)
        
        $i_add += 1
        
        If $a_delim[0] > UBound($a_ret_array, 2) - 1 Then
            ReDim $a_ret_array[$a_lines[0] + 1][$a_delim[0] + 1]
        EndIf
        
        For $j = 1 To $a_delim[0]
            $a_ret_array[$i_add][$j] = $a_delim[$j]
        Next
    Next
    
    If $i_add = 0 Then Return SetError(1, 0, 0)
    ReDim $a_ret_array[$i_add + 1][UBound($a_ret_array, 2)]
    
    $a_ret_array[0][0] = $i_add
    
    Return $a_ret_array
EndFunc

Run this by itself, in the folder you want, replace the $s_my_csv_file string value for the one that is actually your file.

If you get past the first two message boxes, then it will work. If you say it doesn't come up after not getting the first two error message boxes, then your file is corrupt or wrong.

Common sense plays a role in the basics of understanding AutoIt... If you're lacking in that, do us all a favor, and step away from the computer.

Link to comment
Share on other sites

I have no doubt that SmOke_N's code is good, I have a ton of respect for him, but I looked at your first post a bit closer and did this:

$file=fileopen("mc.csv",0)

; Check if file opened for reading OK
If $file = -1 Then
    MsgBox(0, "Error", "Unable to open file.")
    Exit
EndIf


; Read in lines of text until the EOF is reached
While 1
    $line = FileReadLine($file)
    If @error = -1 Then ExitLoop
    $portion = StringSplit($line,",")
    for $value=1 to $portion[0]
        MsgBox(0, "Line read:", $portion[$value])
    Next
Wend

FileClose($file)

There were only a few changes made, so you should be able to look it over and go "Aaaahhhhhhhhhh" :D

Ian

My projects:

  • IP Scanner - Multi-threaded ping tool to scan your available networks for used and available IP addresses, shows ping times, resolves IPs in to host names, and allows individual IPs to be pinged.
  • INFSniff - Great technicians tool - a tool which scans DriverPacks archives for INF files and parses out the HWIDs to a database file, and rapidly scans the local machine's HWIDs, searches the database for matches, and installs them.
  • PPK3 (Persistent Process Killer V3) - Another for the techs - suppress running processes that you need to keep away, helpful when fighting spyware/viruses.
  • Sync Tool - Folder sync tool with lots of real time information and several checking methods.
  • USMT Front End - Front End for Microsoft's User State Migration Tool, including all files needed for USMT 3.01 and 4.01, 32 bit and 64 bit versions.
  • Audit Tool - Computer audit tool to gather vital hardware, Windows, and Office information for IT managers and field techs. Capabilities include creating a customized site agent.
  • CSV Viewer - Displays CSV files with automatic column sizing and font selection. Lines can also be copied to the clipboard for data extraction.
  • MyDirStat - Lists number and size of files on a drive or specified path, allows for deletion within the app.
  • 2048 Game - My version of 2048, fun tile game.
  • Juice Lab - Ecigarette liquid making calculator.
  • Data Protector - Secure notes to save sensitive information.
  • VHD Footer - Add a footer to a forensic hard drive image to allow it to be mounted or used as a virtual machine hard drive.
  • Find in File - Searches files containing a specified phrase.
Link to comment
Share on other sites

You're bordering rediculous with the amount of information you provide.

Run this by itself, in the folder you want, replace the $s_my_csv_file string value for the one that is actually your file.

If you get past the first two message boxes, then it will work. If you say it doesn't come up after not getting the first two error message boxes, then your file is corrupt or wrong.

@SmOke_N

Sorry man. I felt like I was being accused in one of the other replies (not from you but from someone else) that I wasn't providing enough information.

I have no doubt that SmOke_N's code is good, I have a ton of respect for him, but I looked at your first post a bit closer and did this:

There were only a few changes made, so you should be able to look it over and go "Aaaahhhhhhhhhh" :D

Ian

@Ian

I hope I didn't give anyone the impression that I was claiming it was bad code because that wasn't my intent. I know I'm at a level far below you guys. All I could say though is that none of it was working on my computer.

Resolution:

After I made my first and second post I was copying all my files over to a different computer to see if it had something to do with Vista64. Instead of copying the mc.csv file over, I just copied it's contents to a blank text file using notepad. I must've cut the information instead of copying it because when I checked the mc.csv file again a few minutes ago, it was blank. I know the information was there when I made the first 1-2 posts..

The script actually works now. Actually, you're scripts would've worked all along had I double and triple checked the csv file. Normally I don't cut information like that out of any files.

I appreciate your patience with me. Sorry for the trouble. Have a good night. =)

Link to comment
Share on other sites

hehe, I don't think anyone thought you were saying the code suggested was bad, it didn't come off like that.... My only point was that seeing your own code with a few tweaks might be helpful, and though using SmOke_N's code would no doubt have helped, it's helpful to see your own code with some corrections so the point is easier to learn.

Anyway, if nothing else maybe you still got to learn a few new tricks. Hopefully the rest of your script goes well! :D

Ian

My projects:

  • IP Scanner - Multi-threaded ping tool to scan your available networks for used and available IP addresses, shows ping times, resolves IPs in to host names, and allows individual IPs to be pinged.
  • INFSniff - Great technicians tool - a tool which scans DriverPacks archives for INF files and parses out the HWIDs to a database file, and rapidly scans the local machine's HWIDs, searches the database for matches, and installs them.
  • PPK3 (Persistent Process Killer V3) - Another for the techs - suppress running processes that you need to keep away, helpful when fighting spyware/viruses.
  • Sync Tool - Folder sync tool with lots of real time information and several checking methods.
  • USMT Front End - Front End for Microsoft's User State Migration Tool, including all files needed for USMT 3.01 and 4.01, 32 bit and 64 bit versions.
  • Audit Tool - Computer audit tool to gather vital hardware, Windows, and Office information for IT managers and field techs. Capabilities include creating a customized site agent.
  • CSV Viewer - Displays CSV files with automatic column sizing and font selection. Lines can also be copied to the clipboard for data extraction.
  • MyDirStat - Lists number and size of files on a drive or specified path, allows for deletion within the app.
  • 2048 Game - My version of 2048, fun tile game.
  • Juice Lab - Ecigarette liquid making calculator.
  • Data Protector - Secure notes to save sensitive information.
  • VHD Footer - Add a footer to a forensic hard drive image to allow it to be mounted or used as a virtual machine hard drive.
  • Find in File - Searches files containing a specified phrase.
Link to comment
Share on other sites

hehe, I don't think anyone thought you were saying the code suggested was bad, it didn't come off like that.... My only point was that seeing your own code with a few tweaks might be helpful, and though using SmOke_N's code would no doubt have helped, it's helpful to see your own code with some corrections so the point is easier to learn.

Anyway, if nothing else maybe you still got to learn a few new tricks. Hopefully the rest of your script goes well! :D

Ian

Thanks man. I appreciate your help along with everyone else's. Yeah it did help to see my code modified. It's also cool to see another way of doing the same thing.

Just got stuck again on another part of this script so I'm off to start a new thread.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...