Monday, May 12, 2014

Lesson 8 : Solution to the question

Question was to modify the code in the last lesson, where

- the comma could be replaced by tab, for making it easy to read

- to add the columns and show the total.

In  the following code, it takes two parameters, first is csv file, and second is col. The same old file is used. The csv file first

C:\scripts\file-io>type sample.csv
abcd,12,E_123,300
bcde,13,E_124,301
cdef,14,E_125,302
efgh,15,E_126,303
ghij,16,E_127,304
hijk,17,E_128,305
lmno,18,E_129,306
C:\scripts\file-io>

The output of the program

C:\scripts\file-io>03-addcols-csv.vbs sample.csv 4 //nologo
abcd    12      E_123   300
bcde    13      E_124   301
cdef    14      E_125   302
efgh    15      E_126   303
ghij    16      E_127   304
hijk    17      E_128   305
lmno    18      E_129   306

Sum of Col 4 is 2121

And finally the code

Const ReadMode=1
dim fso
dim fstext
dim txtline
dim lines, words
dim strword
dim Oput
dim sums
oput=int(wscript.arguments(1))
set fso=CreateObject("Scripting.FileSystemObject")
set fstext=fso.OpenTextFile(wscript.arguments(0),ReadMode)
sums=0
do until fstext.AtEndOfStream
        txtline=fstext.ReadLine
        strword=split(txtline,",")
        sums=sums+int(strword(oput-1))
        txtline= Replace(txtline,",", vbTab)
        wscript.echo txtline
loop
wscript.echo " "
wscript.echo "Sum of Col " & oput & " is " & sums

What more can be done.

a. You can validate if the column selected exists and if it does exists is it a numeric value.

b. You can check if the csv file passed as a parameter exists in the first place.

No comments: