简体   繁体   中英

How do I add a new column of data to a csv file

I am reading a csv file into a variable data like this:

def get_file(start_file): #opens original file, reads it to array
    with open(start_file,'rb') as f:
        data=list(csv.reader(f))

data is the entire csv file. How do I add an extra column to this data?

data is a list of lists of strings, so...:

for row, itm in zip(data, column):
  row.append(str(itm))

of course you need column to be the right length so you may want to check that, eg raise an exc if len(data) != len(column) .

.append将值添加到data中每行的末尾,然后使用csv.writer写入更新的数据。

Short answer: open up the CSV file in your favourite editor and add a column

Long answer: well, first, you should use csv.reader to read the file; this handles all the details of splitting the lines, malformed lines, quoted commas, and so on. Then, wrap the reader in another method which adds a column.

def get_file( start_file )
    f = csv.reader( start_file )
        def data( csvfile ):
            for line in csvfile:
                 yield line + [ "your_column" ]
    return data( f )

Edit

As you asked in your other question:

def get_file( start_file )
    f = csv.reader( start_file )
        def data( csvfile ):
            for line in csvfile:
                line[ 1 ] += "butter"
                yield line
    return data( f )

which you use like

lines = get_file( "my_file.csv" )
for line in lines:
    # do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM