Add new column to existing csv file

I have a csv file with 5 columns and I want to add data to the 6th column. The data that I have is in an array.

At the moment, the code that I have will insert the data that I would like to receive in the 6th column, only AFTER all the data that already exists in the csv file.

For example, I have:

wind, site, date, time, value 10, 01, 01-01-2013, 00:00, 5.1 89.6 ---> this is the value I want to add in a 6th column but it puts it after all the data from the csv file 

Here is the code I'm using:

 csvfile = 'filename' with open(csvfile, 'a') as output: writer = csv.writer(output, lineterminator='\n') for val in data: writer.writerow([val]) 

I thought using 'a' would add the data to a new column, but instead just put it after (β€œunder”) all the other data ... I don't know what to do!

+6
source share
3 answers

Add data records to the end of the file, not to the end of each line.

Instead, create a new file and add a new value to each line.

 csvfile = 'filename' with open(csvfile, 'r') as fin, open('new_'+csvfile, 'w') as fout: reader = csv.reader(fin, newline='', lineterminator='\n') writer = csv.writer(fout, newline='', lineterminator='\n') if you_have_headers: writer.writerow(next(reader) + [new_heading]) for row, val in zip(reader, data) writer.writerow(row + [data]) 

In Python 2.x, remove the newline='' arguments and change the files from 'r' and 'w' to 'rb' and 'wb' respectively.

Once you verify that this works correctly, you can replace the original file with a new one:

 import os os.remove(csvfile) # not needed on unix os.rename('new_'+csvfile, csvfile) 
+7
source

csv module does not support column entries or additions. Therefore, the only thing you can do is to read from one file, add the data of the sixth column and write to another file. This is shown below:

 with open('in.txt') as fin, open('out.txt', 'w') as fout: index = 0 for line in iter(fin.readline, ''): fout.write(line.replace('\n', ', ' + str(data[index]) + '\n')) index += 1 

data is an int list.

I am testing these codes in python, it works great.

0
source

The mode of adding files to open is designed to add data to the end of the file. you need to give random access to the recording of your file. you need to use seek () method

you can see an example here: http://www.tutorialspoint.com/python/file_seek.htm

or read python docs here: https://docs.python.org/2.4/lib/bltin-file-objects.html , which is not very useful

if you want to add to the end of the column, you can open the file to read the line, find out its length, and then search it to the end.

-1
source

Source: https://habr.com/ru/post/969334/


All Articles