Home > Article > Backend Development > How to Fix Python Script that Skips Lines When Adding a New Column to CSV Files?
You have several CSV files containing data like this:
Name Code blackberry 1 wineberry 2 rasberry 1 blueberry 1 mulberry 2
You want to add a new column named "Berry" to all these files, so that the output will look like this:
Name Code Berry blackberry 1 blackberry wineberry 2 wineberry rasberry 1 rasberry blueberry 1 blueberry mulberry 2 mulberry
However, your current Python script is not working correctly. It skips every line and populates the new column with only the value "Berry".
To solve this issue, you need to modify the code to use the next() function instead of row0 = r.next() (for Python 3, use reader = csv.reader(csvinput)). The updated code:
<code class="python">import csv with open('C:/test/test.csv', 'r') as csvinput: with open('C:/test/output.csv', 'w') as csvoutput: writer = csv.writer(csvoutput, lineterminator='\n') reader = csv.reader(csvinput) all = [] row = next(reader) row.append('Berry') all.append(row) for row in reader: row.append(row[0]) all.append(row) writer.writerows(all)</code>
Notes:
The above is the detailed content of How to Fix Python Script that Skips Lines When Adding a New Column to CSV Files?. For more information, please follow other related articles on the PHP Chinese website!