0

im trying to append a new column to my csv file that looks like that:

column1  column2  column3  column4
   1        1        y
   1        2        3
   w        2        3

if there is a letter at the line I want to append "letter" if there is not appent "no letter" if there is nothing at one of the columns append "one empty"

result:

column1  column2  column3  column4
   1        1        y      letter
   1        2        3     no letter
   w        2              one empty

im trying to do it only with csv module, no panda. thanks!

yuval
  • 169
  • 1
  • 2
  • 8
  • Is there any reason for not doing in pandas? – Pygirl Apr 22 '20 at 06:49
  • [mre]? See [how-to-add-a-new-column-to-a-csv-file](https://stackoverflow.com/questions/11070527/how-to-add-a-new-column-to-a-csv-file) – Patrick Artner Apr 22 '20 at 06:49
  • Hint: open the initial file in read mode and a new file in write mode, read first one with the csv module and consistently append the new value to the row, and write that row to the second one. And show the code... – Serge Ballesta Apr 22 '20 at 06:51
  • 1
    @Pygirl: Unsure for OP, but pandas is a very large module. For operations as simple as this one, it would be a pity to install it if it was not already present. – Serge Ballesta Apr 22 '20 at 06:52

1 Answers1

0

Try:

import csv
csv_data = csv.reader(open('csvfile.csv', 'r'))
csv_new = csv.writer(open('csvfile_new.csv', 'w'))

for i, row in enumerate(csv_data):
    print(i)
    if i==0:
        row.append("column4")
        print(row)
        csv_new.writerow(row)
    else:
        if row[2].isalpha():
            row.append("letter")
        elif row[2].isdigit():
            row.append("no letter")
        else:
            row.append("one empty")
        print(row)
        csv_new.writerow(row)

csvfile.csv:

column1,column2,column3
1,1,y
1,2,3
w,2,

csvfile_new.csv:

column1,column2,column3,column4
1,1,y,letter
1,2,3,no letter
w,2,,one empty
Pygirl
  • 12,969
  • 5
  • 30
  • 43