Replace all values in a certain column with one va

2019-09-04 07:27发布

问题:

Dear Python users in this forum,

I have a data file with large number of columns and rows in ascii format.

This file has mixed data of numbers and letters such as:

 15.20000           120.60000 98327      get data information here.  SURFACE DATA FROM ??????????? SOURCE    FM-12 SYNOP                                                                                155.00000         1         0         0         0         0         T         F         F   -888888   -888888      20020531210000 100880.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0-888888.00000      0

I just put only the part of one line in the file here. My purpose is replace all the value in the certain colum with one value. For example I would like to change all value in column 3 with 999. So I used a code like below:

import csv
with open("SURFACE1", "rb") as infile, open("output.txt", "wb") as outfile:
    reader = csv.reader(infile, delimiter="\t")
    writer = csv.writer(outfile, delimiter="\t")
    for row in reader:
        row[2] = "999" 
        writer.writerow(row)

Howeve it didn't seem to work resulting "out of index error", even though it has more than 30 columns. Any idea or help would be really appreciated.

Thank you, Isaac