Replace/Delete Fields in .CSV files Topic is solved

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
blue_fields
Posts: 20
Joined: 16 Feb 2023, 11:07

Replace/Delete Fields in .CSV files

Post by blue_fields » 20 Mar 2023, 16:35

Hey everyone,

Currently I am able read .csv files in AutoHotkey. But is there a straight forward way to replace or delete fields as well?

This is my code currently which just reads each field line by line. It would be great if I could write the current selected field, but seems like that's not possible. The only other way I can imagine approaching it is doing more complex stuff with the file object and seek/write methods, but then I would have to be counting the individual characters read, and how many characters in a line to get to the first character of the field I'm looking to change, etc. Seems like their could be more eloquent way to do this, any ideas? thank you!

Code: Select all

filePath := "C:\Desktop\mycsv.csv"

Loop Read filePath
{
    MsgBox A_LoopReadLine
    indexL := A_Index
    Loop Parse, A_LoopReadLine, "CSV"
    {
        MsgBox "Index: " . indexL . "`n`n" . "Field: " . A_LoopField
        if (indexL == 1 && A_index == 4) {
            ; A_LoopField := "banana" <--- it would be great if I can do something like this, but the loopfield vatriable can be written to it seems, only read
        }
        
    }
    
}

User avatar
mikeyww
Posts: 26595
Joined: 09 Sep 2014, 18:38

Re: Replace/Delete Fields in .CSV files  Topic is solved

Post by mikeyww » 20 Mar 2023, 17:15

Hello,

AutoHotkey is actually designed to handle this scenario, as Read has an OutputFile parameter for this purpose; see the documentation. Thus, all you need to do is build the text of the line, changing anything you wish, and then use FileAppend to write the line to a different file. When the loop ends, you can copy, move, or rename the file.

Code: Select all

#Requires AutoHotkey v2.0
dir     := A_ScriptDir
inFile  := dir '\mycsv.csv'
outFile := dir '\out.csv'
Try FileRecycle outfile
Loop Read inFile, outfile
{ row := A_Index, line := ''
  Loop Parse A_LoopReadLine, 'CSV'
     (line != '') && line .= ','
   , (comma := InStr(A_LoopField, ',')) && line .= '"'
   , line .= row = 1 && A_Index = 4 ? 'banana' : A_LoopField
   , (comma) && line .= '"'
  FileAppend line '`n'
}
MsgBox 'Done!', 'Status', 64

blue_fields
Posts: 20
Joined: 16 Feb 2023, 11:07

Re: Replace/Delete Fields in .CSV files

Post by blue_fields » 20 Mar 2023, 18:55

Thank you very much. I will study this now! 8-)

blue_fields
Posts: 20
Joined: 16 Feb 2023, 11:07

Re: Replace/Delete Fields in .CSV files

Post by blue_fields » 21 Mar 2023, 12:41

@mikeyww thank you again, understanding this function really helps my scripting for working with csv. It even re-adds the quotes around the fields with commas. amazing!

Post Reply

Return to “Ask for Help (v2)”